sed: remove all leading and ending blank whitespace from a file

Here our requirement is to remove all the whitespace from the leading and ending space per line of a file.

Our sample file /tmp/file
   This is line one
  This is line two
         This is line three
        This is line four

Remove all leading whitespace

To remove all tab whitespace (This will not remove empty space)
# sed 's/^[ ]*//g' /tmp/file
This is line one
This is line two
This is line three
        This is line four
As you see the "tab" space is still there

To remove all leading whitespaces (including tabs)
# sed 's/^[t ]*//g' /tmp/file
This is line one
This is line two
This is line three
This is line four

Remove all trailing whitespace

To remove all trailing whitespaces (including tabs)
# sed -i 's/[t ]*$//g' /tmp/file

Remove both leading and trailing whitespaces

# sed  's/^[t ]*//g;s/[t ]*$//g' /tmp/file

This is line one
This is line two
This is line three
This is line four

Here I have combined both the commands with ";"

Leave a Comment