Remove empty lines from txtfiles, remove spaces from start and end of line

*爱你&永不变心* 提交于 2019-12-03 08:31:39

问题


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:


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)




回答3:


This might work for you:

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



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



来源:https://stackoverflow.com/questions/8562782/remove-empty-lines-from-txtfiles-remove-spaces-from-start-and-end-of-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!