I have a file with a lots of names etc. and with spaces in between. Now, I want to delete all trailing spaces and all empty lines in this file with sed.

I have two commands for this task but I would like to have a combination of both:

sed -i's/\s*$//g' 
sed -i'/^$/d'
  • You mean sed -i 's/.../.../;/^$/d'? – Joseph R. Dec 13 '15 at 22:24
  • sed -ne '/[^ ]/s/ *$//p' – mikeserv Dec 13 '15 at 22:28

With GNU sed (and probably others), you can give multiple commands separated by a semicolon:

sed -i 's/\s*$//g; /^$/d'

Other sed implementations might need you to give the two commands separately with -e:

sed -i -e 's/\s*$//g' -e '/^$/d'

Finally, you could also combine them into a sed script:

$ cat foo.sed

Then, you run it with -f:

$ sed -i -f foo.sed file

this is the command you are looking for:

sed -ne '/[^ ]/s/ *$//p' <in >out

... for lines which match at least least 1 not-space character, sed will susbstitute away the longest match it can make of 0 or more trailing spaces on the tail of the line. if successful (and it always will be, because there's never a shortage of nothing), the line is printed.

the result is that command prints only not-space and not-blank lines while simultaneously trimming all trailing spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.