Delete empty lines and trim surrounding spaces in Bash

This might work for you:

sed -r 's/^\s*(.*\S)*\s*$/\1/;/^$/d' file.txt

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

`s/^ *//`  => left trim
`s/ *$//`  => right trim
`/^$/d`    => remove empty line

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).


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).

Tags:

Bash

Awk

Sed