我希望第 2 列包含字符串 Piebald,其他字符串的顺序并不重要。我有:
HR0024 Black pastel Piebald
HR0028 Piebald
MC0023 Piebald
MC0039 Fire Piebald
MC0075 Piebald VPI Axanthic
MC0082 Pastel Piebald
MC0120 Piebald Yellowbelly Het-Lavender
MC0124 Super-Pastel Piebald Het-Clown
MC0126 Fire Pastel Piebald
MC0144 Piebald Vanilla
我想要这样的东西:
HR0024 Piebald pastel Black
HR0028 Piebald
MC0023 Piebald
MC0039 Piebald Fire
MC0075 Piebald VPI Axanthic
MC0082 Piebald Pastel
MC0120 Piebald Yellowbelly Het-Lavender
MC0124 Piebald Super-Pastel Het-Clown
MC0126 Piebald Pastel Fire
MC0144 Piebald Vanilla
某些行将在不同列(2、3 或 4)上具有目标字符串。我认为cut -f
这里没有这项工作,我认为awk
或者sed
没有必要。任何帮助表示赞赏。
答案1
使用 awk,我们循环遍历字段,如果找到所选字段,则与第二个字段交换。
awk -v p="Piebald" '{
for (i=2;i<=NF;i++) if ($i == p) {$i = $2; $2 = p; break}
}1' file
1
最后的意思是print
线。break
交换后提前退出循环-v var="value"
是将变量传递给 的标准方法awk
。- 此外,通过这种方式,输入中的任何连续空格都会缩小为一个空格,这是默认的输出字段分隔符。
输出:
HR0024 Piebald pastel Black
HR0028 Piebald
MC0023 Piebald
MC0039 Piebald Fire
MC0075 Piebald VPI Axanthic
MC0082 Piebald Pastel
MC0120 Piebald Yellowbelly Het. lavender
答案2
如果其他字符串的顺序不重要,您可以这样做:
$ sed -E 's/Piebald//g; s/^(\S+)/\1 Piebald/' file
HR0024 Piebald Black pastel
HR0028 Piebald
MC0023 Piebald
MC0039 Piebald Fire
MC0075 Piebald VPI Axanthic
MC0082 Piebald Pastel
MC0120 Piebald Yellowbelly Het-Lavender
MC0124 Piebald Super-Pastel Het-Clown
MC0126 Piebald Fire Pastel
MC0144 Piebald Vanilla
或者,如果您sed
不支持:
$ perl -pe 's/Piebald//g; s/^(\S+)/\1 Piebald/' file
HR0024 Piebald Black pastel
HR0028 Piebald
MC0023 Piebald
MC0039 Piebald Fire
MC0075 Piebald VPI Axanthic
MC0082 Piebald Pastel
MC0120 Piebald Yellowbelly Het-Lavender
MC0124 Piebald Super-Pastel Het-Clown
MC0126 Piebald Fire Pastel
MC0144 Piebald Vanilla