A01_106367192 A01_106367192
A01_106359962 A01_106359962
A01_106106644 A01_106106656
A01_106045906 A01_106045909
A01_105865211 A01_105865216
A01_105877866 q
B01_114451441 q
A01_105801529 A01_105801532
A01_105803107 A01_105803079
A01_105803074 A01_105803079
A01_105061789 A01_105061763
A01_105408577 A01_105408577
A01_104975080 A01_104975074
A01_104994687 A01_104994690
A01_104983310 q
A01_104542183 A01_104542186
A01_104652672 q
A01_104652685 A01_104652679
A01_105006416 A01_105006421
A01_105136838 A01_105136837
A01_104359686 q
A01_104359660 A01_104359665
awk '{if ($2 == q) print $1; else print$2 }' input_file |less
按原样返回第 2 列。
答案1
你的代码:
awk '{if ($2 == q) print $1; else print$2 }' input_file
这将打印$1
if$2
等于awk
变量q
。该变量未初始化,因此测试不太可能为真,除非您定义q
为字符串 "q"
在命令行上:
awk -vq="q" '{if ($2 == q) print $1; else print $2 }'
"q"
您可能想要的是与代码本身进行比较:
awk '{if ($2 == "q") print $1; else print $2 }' input_file
或者,用更惯用的方式表达同样的事情:
awk '$2 == "q" { print $1 } $2 != "q" { print $2 }'
或者,
awk '$2 == "q" { print $1; next } { print $2 }'
或者,如RomanPerekrest 的解决方案显示,使用三元?:
运算符。
答案2
短的awk方法:
awk '{ print ($2=="q"? $1:$2) }' file
$2=="q"? $1:$2
- 三元条件,表示:如果表达式$2=="q
计算为true
- 打印左操作数$1
,否则 - 打印右操作数$2
输出:
A01_106367192
A01_106359962
A01_106106656
A01_106045909
A01_105865216
A01_105877866
B01_114451441
A01_105801532
A01_105803079
A01_105803079
A01_105061763
A01_105408577
A01_104975074
A01_104994690
A01_104983310
A01_104542186
A01_104652672
A01_104652679
A01_105006421
A01_105136837
A01_104359686
A01_104359665