Remove empty lines from txtfiles, remove spaces fr

2019-03-12 04:21发布

问题:

Which one would be better:

sed -e '/^$/d' *.txt
sed 'g/^$/d' -i *.txt

Also, how do I remove spaces from beginning and end of each line in the text file?

回答1:

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

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


回答2:

This might work for you:

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


回答3:

Even more simple method using awk.

cat filename.txt | awk 'NF' | awk '{$1=$1;print}'

awk 'NF' - This will remove all blank/empty lines.

awk '{$1=$1;print}' - This will remove only trailing white spaces, (both left and right)



回答4:

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