如何使用linux 命令行刪除文本文件中的空行?
這類似於我們在上一篇文章中介紹的 的方式。我們仍然可以使用sed命令,awk命令和grep命令來完成此操作。
讓我們在下面詳細查看操作示例。
以下內容是測試文件的內容,我們將使用以下內容進行示例演示。
<code>hello, this is an example of deleting empty lines in a text file.
Use the sed command to delete empty lines.
Use the awk command to delete empty lines.
Use the grep command to delete empty lines./<code>
使用awk命令刪除文件中的空行
在下面的示例中,我們將使用awk命令NF變量來檢測當前行中的字段數。如果數字為0,則表示當前行為空行。
<code>➜ ~ awk '{if(NF>0) {print $0}}' text.log
# OR
➜ ~ awk '!/^$/' text.log/<code>
您使用 awk 'NF' test.log 命令也達到同樣的目的。
使用sed命令刪除文件中的空行
在下面的示例中,我們將使用sed命令正則表達式來檢查當前行是否為空白。如果當前行為空,請刪除當前行。
<code>➜ ~ sed '/^$/d' text.log
/<code>
使用grep命令刪除文件中的空行
在以下示例中,我們將使用grep命令-v選項排除匹配的空行,然後使用“>”將數據輸出到新文件。
<code>➜ ~ grep -v '^$' text.log
➜ ~ grep -v '^$' text.log > newFile.log/<code>
閱讀更多 閃電小白獸 的文章