You can use bash to do simple substitutions of variables, just like you can with sed. The bash trick turns out to take up less characters (bytes).

Lets set some variable

VAR1="this is a sentence"

To replay it back:

echo $VAR1

or

echo ${VAR1}

Output of both:

this is a sentence

 

Format

To do a simple substitution of the value/contents of a variable structure it like so. Put in the from part the thing you want to change (it can be a char or some chars), then it will replace them with the part you put in to (which can be a char or several chars). Note if mentioning special chars to escape them (example \ needs to be \\). Spaces are not considered special chars in this case.

echo ${VAR//from/to}

Then all of the parts that are from will change to to when the variable VAR is called.

Example 1

Lets replace all s with a S. You have to use the second notation type and add some parameters

echo "${VAR1//s/S}"

Output:

thiS iS a Sentence
  • Note: sed can be used to do the same substitutions
echo "$VAR1" | sed 's|s|S|g'

or

echo "$VAR1" | sed 's/s/S/g'

 

Example 2

Let replace all is with IZ

echo "${VAR1//is/IZ}"

Output:

thIZ IZ a sentence
  • Note: sed can be used to do the same substitutions
echo "$VAR1" | sed 's|is|IZ|g'

or

echo "$VAR1" | sed 's/is/IZ/g'

 

Example 3 – filenames with spaces

What about converting an absolute path which has spaces to something with escaped spaces (backslash followed by space)

SOMEDIR="/root/yearly projects/of the year 2017/january/"
echo "${SOMEDIR}"

Output:

/root/yearly projects/of the year 2017/january/

We convert spaces ” ” to “\ ” however in bash to print a backslash “\” we need to put an extra one “\\”

echo "${SOMEDIR// /\\ }"

Output:

/root/yearly\ projects/of\ the\ year\ 2017/january/
  • Note: sed can be used to do the same substitutions
echo "$SOMEDIR" | sed 's| |\\ |g'

or

echo "$SOMEDIR" | sed 's/ /\\ /g'

The end.

Leave a Reply

Your email address will not be published. Required fields are marked *