Penguin

Two Methods For Finding The Length Of a String

  • test="This is a string"

Method 1)

  • echo ${#test}

Method 2)

  • expr length test

Both will give you the correct length of 16.

How can I get a substring of a variable?

Say the variable test contains the string "corndog" but we want just the "dog" part.

echo ${test:4:3} will return just "dog"

The 4 tells us the index of the char that will be the first char in the substring. The 3 tells us how many letters to add starting at the index.

Remove Substrings (uses bash's pattern matching)

Strips shortest match of $substring from front of $string.

  • ${string#substring}

For example if $string contained "This is a string" and we replaced substring with T* an echo would result in his is a string

Strips longest match of $substring from front of $string.

  • ${string##substring}

For example if $string contained "This is a string" and we replaced substring with T* an echo would result in an empty string. (The longest match was the entire string).

Strips shortest match of $substring from back of $string.

  • ${string%substring}

For example if $string contained "This is a string" and we replaced substring with s* an echo would result in This is a

Strips longest match of $substring from back of $string.

  • ${string%%substring}

For example if $string contained "This is a string" and we replaced substring with s* an echo would result in Thi (The longest match)

Concatenate variables.

  • echo ${string1}${string2}

If we did:

  • echo $string1string2

then bash would be looking for a variable called string1string2 (which does not exist). This is why the curly brackets are necessary.

Another Example:

  • echo ${string1}"Some more Text"

Brace Expansion

  • echo C{a,u,o}t

Will return Cat Cut Cot

Another example of where this could be useful:

  • mkdir ~/test/{cat,dog,rabbit}

This will create a cat , dog and rabbit dir in ~/test/