This command removes empty lines:
sed -e '/^$/d' file
But, how do I remove spaces from beginning and end of each non-empty line?
To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use the command ' grep -f /dev/null '.
$ 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With