如果它们存在于第二列中,我需要一一搜索数千个字符串,如果不存在,则对在任何行的第二列中找不到的每个此类字符串执行操作
文件:
line a
line b
line c
line z
line d
line e
line z
line z
文件2:
line a
line b
line c
line d
line e
我尝试过的:
$ awk '{if($2=="z") {c++} } END { if(c==0) {print "no \"z\""} else { print c" \"z\"" }}' file
3 "z"
$ awk '{if($2=="z") {c++} } END { if(c==0) {print "no \"z\""} else { print c" \"z\"" }}' file2
no "z"
$ awk '{if($2=="z") {c++} } END { if(c!=0) {print "no \"z, action will be done\""} }' file
no "z, action will be done"
我的代码可以吗,或者可以简化/优化吗?
更新:@RomanPerekhrest 指的是您的代码,如何仅处理“else”或向“c”添加否定?然后忽略其他?
我正在尝试:(c?:“不”),
但它不起作用。
@αГsнιη,谢谢你,我终于有了工作脚本
$ awk -v s="z" '$2==s{ c++ }END{ printf (!c ? NOP : "prepare command1\nprepare command2\nprepare command3\n") }' file
prepare command1
prepare command2
prepare command3
$ awk -v s="z" '$2==s{ c++ }END{ printf (!c ? NOP : "prepare command1\nprepare command2\nprepare command3\n") }' file2
$
或者
$ awk -v s="z" '$2==s{ c++ }END{if(c==0) printf "prepare command1\nprepare command2\nprepare command3\n" }' file2
prepare command1
prepare command2
prepare command3
$ awk -v s="z" '$2==s{ c++ }END{if(c==0) printf "prepare command1\nprepare command2\nprepare command3\n" }' file
$
答案1
通过awk
动态变量/参数-v <var>=<value>
:
字符串的测试用例z
:
awk -v s="z" '$2==s{ c++ }END{ printf "%s \042%s\042\n", (c? c : "no"), s }' file
输出:
3 "z"
字符串的测试用例w
:
awk -v s="w" '$2==s{ c++ }END{ printf "%s \042%s\042\n", (c? c : "no"), s }' file
输出:
no "w"
答案2
如果我正确理解这一点,您想检查第二列是否有特定的字母表,如果是,所以请尝试下面的awk
脚本,该脚本将报告哪一个存在并具有相应的计数,哪一个不带有"NOT FOUND!"
备注。
awk -v alphabet="$(printf "%s" {a..z})" 'BEGIN{ split(alphabet, arr, "") }
{ chrs[$2]++ } END{ for(y in chrs) for(x in arr)
{ if(arr[x] in chrs) {print y, chrs[y]; delete arr[x]; break }
else{ print arr[x]" NOT FOUND!"; delete arr[x] }
}
}' infile
输出:
w 1
z 3
a 1
b 1
c 1
f NOT FOUND!
g NOT FOUND!
h NOT FOUND!
i NOT FOUND!
j NOT FOUND!
k NOT FOUND!
l NOT FOUND!
m NOT FOUND!
n NOT FOUND!
o NOT FOUND!
p NOT FOUND!
q NOT FOUND!
r NOT FOUND!
s NOT FOUND!
t NOT FOUND!
u NOT FOUND!
v NOT FOUND!
d 1
x NOT FOUND!
y NOT FOUND!
e 1