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
  • 1
  • 16
  • 47
  • 69
alvas
  • 115,346
  • 109
  • 446
  • 738

4 Answers4

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

`s/^ *//`  => left trim
`s/ *$//`  => right trim
`/^$/d`    => remove empty line
kev
  • 155,172
  • 47
  • 273
  • 272
  • 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
9

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
  • 1
  • 16
  • 47
  • 69
M.S. Arun
  • 1,053
  • 13
  • 22
4

This might work for you:

sed -r 's/^\s*(.*\S)*\s*$/\1/;/^$/d' file.txt
potong
  • 55,640
  • 6
  • 51
  • 83
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
  • 155,785
  • 88
  • 678
  • 743