Linux AWK 去除空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10347653/
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
AWK remove blank lines
提问by general exception
The /./
is removing blank lines for the first condition { print "a"$0 }
only, how would I ensure the script removes blank lines for every condition ?
该/./
被删除空行的第一个条件{ print "a"$0 }
而已,我怎么会确保每个条件的脚本删除空行?
awk -F, '/./ { print "a"awk -F, '
/./ {
print "a"/^$/ {next}
;
if (NR!=1) { print "b"awk 'NF > 0' filename
}
print "c"awk NF file
}
END { print "d"awk '!/^$/' file
}
' MyFile
} NR!=1 { print "b"##代码## } { print "c"##代码## } END { print "d"##代码## }' MyFile
采纳答案by Birei
Put following conditions inside the first one, and check them with if
statements, like this:
将以下条件放在第一个条件中,并使用if
语句检查它们,如下所示:
回答by glenn Hymanman
if you want to ignore all blank lines, put this at the beginning of the script
如果要忽略所有空行,请将其放在脚本的开头
##代码##回答by Aaykay
Awk command to remove blank lines from a file:
从文件中删除空行的 awk 命令:
##代码##回答by oliv
A shorter form of the already proposed answer could be the following:
已经提出的答案的较短形式可能如下:
##代码##Any awk
script follows the syntax condition {statement}
. If the statement block is not present, awk
will print the whole record (line) in case the condition
is not zero.
任何awk
脚本都遵循语法condition {statement}
。如果语句块不存在,awk
则在condition
不为零的情况下打印整个记录(行)。
NF
variable in awk
holds the number of fields in the line. So when the line is non empty, NF
holds a positive value which trigger the default awk
action (print the whole line). In case of empty line, NF
is zero and the condition is not met, so awk
does nothing.
NF
变量 inawk
保存行中的字段数。因此,当该行非空时,NF
持有一个正值,触发默认awk
操作(打印整行)。在空行的情况下,NF
为零且不满足条件,因此awk
什么也不做。
Note that you don't even need quote because this 2 letters awk script doesn't contain any space or character that could be interpreted by the shell.
请注意,您甚至不需要引号,因为这个 2 个字母的 awk 脚本不包含任何可以被 shell 解释的空格或字符。
or
或者
##代码##^$
is the regex for an empty line. The 2 /
is needed to let awk
understand the string is a regex. !
is the standard negation.
^$
是空行的正则表达式。/
需要2才能awk
理解字符串是正则表达式。!
是标准否定。