Remove whitespace in a file in Linux bash

Home > Search
  by

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 beggining of a line with nothing".

~]# cat example.txt | sed 's|^[ \s]*||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 in the box below so that we can be sure you are a human.




Comments