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

Updated:   |  Bash (Scripting) articles

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

   Hello
  World
       Hello
    World

 

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

~]# declare -p foo
declare -- foo="bar "

 

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 4a4693 in the box below so that we can be sure you are a human.