我有一个awk
命令,如下所示:
awk -F ',' '{print $3 "," $4 "," $2 ", " $1 "," $5 "," $6}
它很好用,除了它适用于文件中的每一行,我不需要。我想限制它只适用于包含特定模式的行。所以我输入另一个命令:
(awk -F ',' '{print $3 "," $4 "," $2 ", " $1 "," $5 "," $6} | awk '/mypattern/')
这样可行,但现在只打印 包含该模式的行并删除不合适的行。
我希望将命令限制为只使用包含模式的行,并保留不包含模式的行。似乎可以使用if语句,但我无法弄清楚如何使用我当前的代码来集成awk
的条件语法。
答案 0 :(得分:2)
awk -F ',' '/mypattern/ {print $3 "," $4 "," $2 ", " $1 "," $5 "," $6} !/mypattern/'
除了:你的例子中有subshell的原因吗?即( awk -F ',' ... )
?
答案 1 :(得分:2)
鉴于file.csv
包含:
1,2,3,4,5,6
1,2,3boo,4,5,6
试试这个awk:
$ awk -F ',' '{
if (/boo/)
print $3 "," $4 "," $2 ", " $1 "," $5 "," $6
else
print $0
}' "file.csv"
成功结果:
1,2,3,4,5,6
3boo,4,2, 1,5,6
/boo/
是匹配的示例模式if (condition)
... else
{
}
来简化else
,要按原样保留该行而不更改它,我们使用print $0
打印整行答案 2 :(得分:2)
awk
救援!
相同的解决方案,更具惯用性
$ awk -F, 'BEGIN{OFS=FS} /pat/{print $3,$4,$2,$1,$5,$6; next}1' file
1,2,3,4,5,6
3,4,2,1,pat,6
1,2,3,4,5,6
表示输入文件
$ cat file
1,2,3,4,5,6
1,2,3,4,pat,6
1,2,3,4,5,6