Use Sed to Delete All Leading/Following Blank Spaces in a Text File

Use sed to delete all leading/following blank spaces in a text file

You almost got it:

sed -e 's/^[ \t]*//;s/[ \t]*$//' a > c

Moreover on some flavours of sed, there is also an option for editing inline:

sed -i -e 's/^[ \t]*//;s/[ \t]*$//' a

Bash - How to remove all white spaces from a given text file?

$ man tr
NAME
tr - translate or delete characters

SYNOPSIS
tr [OPTION]... SET1 [SET2]

DESCRIPTION
Translate, squeeze, and/or delete characters from standard
input, writing to standard output.

In order to wipe all whitespace including newlines you can try:

cat file.txt | tr -d " \t\n\r" 

You can also use the character classes defined by tr (credits to htompkins comment):

cat file.txt | tr -d "[:space:]"

For example, in order to wipe just horizontal white space:

cat file.txt | tr -d "[:blank:]"

SED Command to remove first digits and spaces of each line

Your sed command would be,

sed 's/.* //g' file

This would remove the first numbers along with the space followed.

How to remove trailing whitespaces with sed?

Thanks to codaddict for suggesting the -i option.

The following command solves the problem on Snow Leopard

sed -i '' -e's/[ \t]*$//' "$1"

How to remove leading whitespace from each line in a file

sed "s/^[ \t]*//" -i youfile

Warning: this will overwrite the original file.

remove white space from the end of line in linux

Use either a simple blank * or [:blank:]* to remove all possible spaces at the end of the line:

sed 's/ *$//' file

Using the [:blank:] class you are removing spaces and tabs:

sed 's/[[:blank:]]*$//' file

Note this is POSIX, hence compatible in both GNU sed and BSD.

For just GNU sed you can use the GNU extension \s* to match spaces and tabs, as described in BaBL86's answer. See POSIX specifications on Basic Regular Expressions.


Let's test it with a simple file consisting on just lines, two with just spaces and the last one also with tabs:

$ cat -vet file
hello $
bye $
ha^I $ # there is a tab here

Remove just spaces:

$ sed 's/ *$//' file | cat -vet -
hello$
bye$
ha^I$ # tab is still here!

Remove spaces and tabs:

$ sed 's/[[:blank:]]*$//' file | cat -vet -
hello$
bye$
ha$ # tab was removed!

Remove Leading Whitespace from File

Using the same source as Dav:

# delete all leading blank lines at top of file
sed '/./,$!d'

Source: http://www.linuxhowtos.org/System/sedoneliner.htm?ref=news.rdf

Additionally, here's why this works:

The comma separates a "range" of operation. sed can accept regular expressions for range definitions, so /./ matches the first line with "anything" (.) on it and $ specifies the end of the file. Therefore,

  • /./,$ matches "the first not-blank line to the end of the file".
  • ! then inverts that selection, making it effectively "the blank lines at the top of the file".
  • d deletes those lines.


Related Topics



Leave a reply



Submit