Linux 通过 grep 删除文本文件中的空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1611809/
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
Remove empty lines in a text file via grep
提问by user191960
FILE
:
FILE
:
hello
world
foo
bar
How can I remove all the empty new lines in this FILE
?
如何删除此中的所有空新行FILE
?
Output of command:
命令的输出:
FILE
:
FILE
:
hello
world
foo
bar
采纳答案by DigitalRoss
grep . FILE
grep . FILE
(And if you really want to do it in sed, then: sed -e /^$/d FILE
)
(如果你真的想这样做在sed,则:sed -e /^$/d FILE
)
(And if you really want to do it in awk, then: awk /./ FILE
)
(如果你真的想这样做的AWK,然后:awk /./ FILE
)
回答by Mr.Ree
Try the following:
请尝试以下操作:
grep -v -e '^$'
回答by ghostdog74
with awk, just check for number of fields. no need regex
$ more file
hello
world
foo
bar
$ awk 'NF' file
hello
world
foo
bar
回答by clblue2000
grep '^..' my_file
grep '^..' my_file
example
例子
THIS
IS
THE
FILE
EOF_MYFILE
it gives as output only lines with at least 2 characters.
它只提供至少有 2 个字符的行作为输出。
THIS
IS
THE
FILE
EOF_MYFILE
See also the results with grep '^' my_file
outputs
另请参阅grep '^' my_file
输出结果
THIS
IS
THE
FILE
EOF_MYFILE
and also with grep '^.' my_file
outputs
还有grep '^.' my_file
输出
THIS
IS
THE
FILE
EOF_MYFILE
回答by Prabhat Kumar Singh
Try this: sed -i '/^[ \t]*$/d' file-name
尝试这个: sed -i '/^[ \t]*$/d' file-name
It will delete all blank lines having any no. of white spaces (spaces or tabs) i.e. (0 or more) in the file.
它将删除所有没有任何空行。文件中的空格(空格或制表符),即(0 个或更多)。
Note: there is a 'space' followed by '\t' inside the square bracket.
注意:方括号内有一个“空格”后跟“\t”。
The modifier -i
will force to write the updated contents back in the file. Without this flag you can see the empty lines got deleted on the screen but the actual file will not be affected.
修改器-i
将强制将更新的内容写回到文件中。如果没有这个标志,您可以看到屏幕上的空行被删除,但实际文件不会受到影响。
回答by kenorb
回答by Chris Koknat
Perl might be overkill, but it works just as well.
Perl 可能有点矫枉过正,但它也能正常工作。
Removes all lines which are completely blank:
删除所有完全空白的行:
perl -ne 'print if /./' file
Removes all lines which are completely blank, or only contain whitespace:
删除所有完全空白或仅包含空格的行:
perl -ne 'print if ! /^\s*$/' file
Variation which edits the original and makes a .bak file:
编辑原始文件并制作 .bak 文件的变体:
perl -i.bak -ne 'print if ! /^\s*$/' file
回答by Marco Coutinho
Here is a solution that removes all lines that are either blank or contain only space characters:
这是一个删除所有空白或仅包含空格字符的行的解决方案:
grep -v '^[[:space:]]*$' foo.txt
回答by kenorb
If removing empty lines means lines including any spaces, use:
如果删除空行意味着行包含任何空格,请使用:
grep '\S' FILE
For example:
例如:
$ printf "line1\n\nline2\n \nline3\n\t\nline4\n" > FILE
$ cat -v FILE
line1
line2
line3
line4
$ grep '\S' FILE
line1
line2
line3
line4
$ grep . FILE
line1
line2
line3
line4
See also:
也可以看看: