Linux 如何使用awk忽略空行和注释行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11267015/
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-08-06 07:10:00  来源:igfitidea点击:

how to ignore blank lines and comment lines using awk

regexlinuxbashawk

提问by phani

i am writing this code:

我正在写这个代码:

awk -F'=' '!/^$/{arr[]=}END{for (x in arr) {print x"="arr[x]}}' 1.txt 2.txt

this code ignore blank lines, but i also want to ignore line starting with # (comments).

此代码忽略空行,但我也想忽略以#(注释)开头的行。

Any idea how to add multiple patterns?

知道如何添加多个模式吗?

采纳答案by chaos

Change !/^$/to

更改!/^$/

!/^($|#)/

or

或者

!/^($|[:space:]*#)/

if you want to disregard whitespace before the #.

如果您想忽略#.

回答by Levon

awk 'NF && !~/^#/' data.txt

Will print all non-blank lines (number of fields NFis not zero) and lines that don't contain #as the first field.

将打印所有非空白行(字段NF数不为零)和不包含#作为第一个字段的行。

It will handle a line of whitespace correctly since NF will be zero, and leading blanks since $1will ignore them.

它将正确处理一行空格,因为 NF 将为零,并且前导空格$1将忽略它们。

回答by Jaap

awk 'NF && !/^[:space:]*#/' data.txt

Because '[:space:]*' catches noneor more spaces.

因为 '[:space:]*' 捕获一个或多个空格。