FreeKB - Bash Shell Scripting whitespace \s
Bash Shell Scripting - whitespace \s

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

 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |