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?
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?
$ sed 's/^ *//; s/ *$//; /^$/d' file.txt
`s/^ *//` => left trim
`s/ *$//` => right trim
`/^$/d` => remove empty line
This might work for you:
sed -r 's/^\s*(.*\S)*\s*$/\1/;/^$/d' file.txt
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)
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
).