21

This command removes empty lines:

sed -e '/^$/d' file

But, how do I remove spaces from beginning and end of each non-empty line?

oguz ismail
  • 39,105
  • 12
  • 41
  • 62
alvas
  • 105,505
  • 99
  • 405
  • 683

4 Answers4

41
$ sed 's/^ *//; s/ *$//; /^$/d' file.txt

`s/^ *//`  => left trim
`s/ *$//`  => right trim
`/^$/d`    => remove empty line
kev
  • 146,428
  • 41
  • 264
  • 265
  • 4
    `sed -r 's/^\s*//; s/\s*$//; /^$/d'` – kev Dec 19 '11 at 14:56
  • `sed -r "/^\s*\$/d ; s@^\s*(.*)\s*\$@\1@"` - less `sed`-"calling" :) – uzsolt Dec 19 '11 at 18:36
  • 1
    Note to OS X users: the equivalent answer is `sed -E 's/^ +//; s/ +$//; /^$/d' file.txt` (the equivalent to the generalized, `\s`-based variant is: `sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//; /^$/d' file.txt`. (There is no `-r` option for `sed` on OS X (as of 10.8); `-E` turns on extended regular expressions, which support `[[:..:]]`-style character classes, but apparently not their shorthand equivalents such as `\s`.) – mklement0 Aug 28 '12 at 02:47
  • This can be slightly improved with the accepted answer here: http://stackoverflow.com/questions/16414410/delete-empty-lines-using-sed/24957725#24957725 – ConMan Jul 25 '14 at 14:11
  • rather than space it might be better to use [[:blank:]] which includes also tabs – Petr Kozelka Dec 13 '14 at 02:06
8

Even more simple method using awk.

awk 'NF { $1=$1; print }' file

NF selects non-blank lines, and $1=$1 trims leading and trailing spaces (with the side effect of squeezing sequences of spaces in the middle of the line).

oguz ismail
  • 39,105
  • 12
  • 41
  • 62
M.S. Arun
  • 773
  • 10
  • 21
4

This might work for you:

sed -r 's/^\s*(.*\S)*\s*$/\1/;/^$/d' file.txt
potong
  • 51,370
  • 6
  • 49
  • 80
2

Similar, but using ex editor:

ex -s +"g/^$/de" +"%s/^\s\+//e" +"%s/\s\+$//e" -cwq foo.txt

For multiple files:

ex -s +'bufdo!g/^$/de' +'bufdo!%s/^\s\+//e' +'bufdo!%s/\s\+$//e' -cxa *.txt

To replace recursively, you can use a new globbing option (e.g. **/*.txt).

kenorb
  • 137,499
  • 74
  • 643
  • 694