Bootstrap FreeKB - Bash (Scripting) - Replacing whitespace
Bash (Scripting) - Replacing whitespace

Updated:   |  Bash (Scripting) articles

declare can be used to determine if a variable contains whitespace. In this example, the foo variable contains whitespace.

~]# foo=" Hello World "
~]# declare -p foo
declare -- foo=" Hello World "

 

Sometimes, redefining the variable may remove whitespace before and after the value of the variable but should not remove whitespace within the value of the variable.

~]$ foo=" Hello World "
~]$ declare -p foo
declare -- foo=" Hello World "

~]$ foo=$(echo $foo)
~]$ declare -p foo
declare -- foo="Hello World"

 

If you want to remove all whitespace in a variable, you can try using sed. 

~]$ foo=" Hello World "
~]$ declare -p foo
declare -- foo=" Hello World "

~]$ foo=$(echo $foo | sed 's|\s*||g')
~]$ declare -p foo
declare -- foo="HelloWorld"

 

And here is an example of how to remove whitespace between the elements in a list.

~]$ array=(foo bar)
~]$ echo \"${array[*]}\"
"foo bar"

~]$ newarray=$(echo ${array[*]} | sed 's|\s*||g')
~]$ echo \"${newarray[*]}\"
"foobar"

 

Let's say example.txt has unpredictable whitespace before and after text.

   Hello
  World
       Hello
    World

 

The following sed command will eliminate the white space to the left of text, so that all of the text is left justified. The literal intpretation of this is "Replace whitespace [ \s]* at the begining of a line with nothing".

~]# cat example.txt | sed 's|^\s*||g'
Hello
World
Hello
World

 

Or, sometimes this syntax works better.

~]# cat example.txt | sed -e 's|^[[:space:]]\+||g'
Hello
World
Hello
World

 

The following sed command will eliminate the white space to the right of text, so that all of the text does not contain any trailing white space. The literal intpretation of this is "Replace whitespace [ \s]* at the end of a line $ with nothing".

~]# cat example.txt | sed 's|\s*$||g'
Hello
World
Hello
World

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter dae033 in the box below so that we can be sure you are a human.