linux下删除文本中所有空行的几种方法(Several methods of deleting all blank lines in text under Linux)

方法一:利用grep

grep -v ‘^\s*$’ test.txt

注:-v表示将匹配的结果进行反转,正则表达式匹配空行。(空行可包括空格符制表符等空白字符)

方法二:利用sed

sed ‘/^\s*$/d’ test.txt

注:d代表删除该行

方法三:利用awk

awk NF test.txt

注:NF代表当前行的字段数,空行的话字段数为0,被awk解释为假,因此不进行输出。

————————

Method 1: using grep

grep -v ‘^\s*$’ test.txt

Note: – V means to invert the matching result, and the regular expression matches the empty line. (blank lines can include white space characters such as space characters and tabs)

Method 2: using sed

sed ‘/^\s*$/d’ test.txt

Note: D means to delete this line

Method 3: using awk

awk NF test.txt

Note: NF represents the number of fields in the current line. If there is an empty line, the number of fields is 0, which is awk interpreted as false, so it will not be output.