This command removes empty lines:
sed -e '/^$/d' file
But, how do I remove spaces from beginning and end of each non-empty line?
This command removes empty lines:
sed -e '/^$/d' file
But, how do I remove spaces from beginning and end of each non-empty line?
$ sed 's/^ *//; s/ *$//; /^$/d' file.txt
`s/^ *//` => left trim
`s/ *$//` => right trim
`/^$/d` => remove empty line
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).
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
).