bash 如果列为空,awk 会打印一些内容

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

awk print something if column is empty

bashawksed

提问by prabhu

I am trying out one script in which a file [ file.txt ] has so many columns like

我正在尝试一个脚本,其中文件 [file.txt] 有很多列,例如

abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha| |325
xyz| |abc|123

I would like to get the column list in bash script using awk command if column is empty it should print blankelse print the column value

我想使用 awk 命令获取 bash 脚本中的列列表,如果列为空,则应打印为空白,否则打印列值

I have tried the below possibilities but it is not working

我已经尝试了以下可能性,但它不起作用

cat file.txt | awk -F "|" {'print '} | sed -e 's/^$/blank/' // Using awk and sed
cat file.txt | awk -F "|" '! {print "blank"} '
cat file.txt | awk -F "|" '{if  ( =="" ) print "blank" } '

please let me know how can we do that using awk or any other bash tools.

请让我知道我们如何使用 awk 或任何其他 bash 工具来做到这一点。

Thanks

谢谢

回答by Arjun Mathew Dan

You can do it using this sedscript:

您可以使用此sed脚本执行此操作:

sed -r 's/\| +\|/\|blank\|/g' File
abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha|blank|325
xyz|blank|abc|123

If you don't want the |:

如果你不想要|

sed -r 's/\| +\|/\|blank\|/g; s/\|/ /g' File
abc pqr lmn 123
pqr xzy 321 azy
lee cha blank 325
xyz blank abc 123

Else with awk:

否则awk

awk '{gsub(/\| +\|/,"|blank|")}1' File
abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha|blank|325
xyz|blank|abc|123

回答by rici

I think what you're looking for is

我想你要找的是

awk -F '|' '{print match(, /[^ ]/) ?  : "blank"}' file.txt

match(str, regex)returns the position in strof the first match of regex, or 0 if there is no match. So in this case, it will return a non-zero value if there is some non-blank character in field 2. Note that in awk, the index of the first character in a string is 1, not 0.

match(str, regex)返回str正则表达式第一个匹配项的位置,如果没有匹配项,则返回0。所以在这种情况下,如果字段 2 中有一些非空白字符,它将返回一个非零值。 注意在 awk 中,字符串中第一个字符的索引是 1,而不是 0。

Here, I'm assuming that you're interested only in a single column.

在这里,我假设您只对单个列感兴趣。

If you wanted to be able to specify the replacement string from a bash variable, the best solution would be to pass the bash variable into the awk program using the -vswitch:

如果您希望能够从 bash 变量中指定替换字符串,最好的解决方案是使用-vswitch将 bash 变量传递给 awk 程序:

awk -F '|' -v blank="$replacement" \
    '{print match(, /[^ ]/) ?  : blank}' file.txt

This mechanism avoids problems with escaping metacharacters.

这种机制避免了转义元字符的问题。

回答by anubhava

You can use awk like this:

您可以像这样使用 awk:

awk 'BEGIN{FS=OFS="|"} {for (i=1; i<=NF; i++) if ($i ~ /^ *$/) $i="blank"} 1' file
abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha|blank|325
xyz|blank|abc|123