bash 从txtfiles中删除空行,从行首和行尾删除空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8562782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:23:10  来源:igfitidea点击:

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

bashsedtext-filesspacesreplace

提问by alvas

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?

另外,如何从文本文件中每行的开头和结尾删除空格?

回答by kev

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

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

回答by M.S. Arun

Even more simple method using awk.

使用awk的更简单的方法。

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

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

awk 'NF'- 这将删除所有空白/空行。

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

awk '{$1=$1;print}'- 这将只删除尾随空格,(左右)

回答by potong

This might work for you:

这可能对你有用:

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

回答by kenorb

Similar, but using exeditor:

类似,但使用ex编辑器:

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

要递归替换,您可以使用新的 globbing 选项(例如**/*.txt)。