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 ";"

1 thought on “sed: remove all leading and ending blank whitespace from a file”

  1. Hi everybody, Thanks you all, I used your very useful idea.
    I have a problem with my bash scripting, it is:
    I have several files in several directories. At the beginning of each line there are few blank spaces, one, two, three, tab and more. These blank space are fine,I want to keep them.
    but inside each line there are also blank spaces which I want to delete all of them. I am using sed, tr, ed commands but they delete also the Blank spaces through all the lines and the files, I do not want to delete the blank spaces at the beginning of the lines,
    I appreciate if someone can help me.
    Regards
    Shirzad

    Reply

Leave a Comment