awk如何只在第2列空单元格中找到并替换为文本

时间:2014-12-20 07:22:42

标签: shell awk sed grep

我有以下输入

server01, 
server02, 
server03, 
server04, windows 2008 R2 USA
server05, Linux Centos Canada
server06, 
server07, 
server08, Linux RedHat UK
server09, 
server10, 
...

我需要命令只替换第2列中没有任何内容的行和text,以获得以下输出:

server01, Incomplete
server02, Incomplete
server03, Incomplete
server04, windows 2008 R2 USA
server05, Linux Centos Canada
server06, Incomplete
server07, Incomplete
server08, Linux RedHat UK
server09, Incomplete
server10, Incomplete
...

非常感谢你的帮助

5 个答案:

答案 0 :(得分:4)

您可以尝试使用此sed命令

sed 's/, $/&Incomplete/' FileName

server01之后没有空格,尝试*出现零次或多次

sed 's/, *$/&Incomplete/' 

输出

server01, Incomplete
server02, Incomplete
server03, Incomplete
server04, windows 2008 R2 USA
server05, Linux Centos Canada
server06, Incomplete
server07, Incomplete
server08, Linux RedHat UK
server09, Incomplete
server10, Incomplete

答案 1 :(得分:1)

尝试类似:

awk '{if (!$2) {print $1, "Incomplete"} else {print $1, $2}}' myfile.txt

输出:

server01, Incomplete
server02, Incomplete
server03, Incomplete
server04, windows 2008 R2 USA
server05, Linux Centos Canada
server06, Incomplete
server07, Incomplete
server08, Linux RedHat UK
server09, Incomplete
server10, Incomplete

答案 2 :(得分:1)

使用bash:

while IFS=, read -r A B; do echo -n "$A,"; [[ $B == " " ]] && echo " Incomplete" || echo "$B"; done

输出:

server01, Incomplete
server02, Incomplete
server03, Incomplete
server04, windows 2008 R2 USA
server05, Linux Centos Canada
server06, Incomplete
server07, Incomplete
server08, Linux RedHat UK
server09, Incomplete
server10, Incomplete

答案 3 :(得分:1)

这是awk

awk 'NF==1{$0=$0"incomplete"}1' file
server01, incomplete
server02, incomplete
server03, incomplete
server04, windows 2008 R2 USA
server05, Linux Centos Canada
server06, incomplete
server07, incomplete
server08, Linux RedHat UK
server09, incomplete
server10, incomplete

如果只有一个字段,请添加额外的文字。


以下是另一种变体:

awk '!$2{print $1,"Incomplete";next}1' file

答案 4 :(得分:1)

这就是你需要的:

awk -F, '{print $0 ($2=="" ? "Incomplete" : "")}' file

所有其他当前发布的awk解决方案都将失败,给定一些特定值$ 1和/或$ 2(例如,如果$ 2的数值为零或$ 1包含空格或......)。