![重新排列列的顺序,以便特定列获得相同的字符串](https://linux22.com/image/182577/%E9%87%8D%E6%96%B0%E6%8E%92%E5%88%97%E5%88%97%E7%9A%84%E9%A1%BA%E5%BA%8F%EF%BC%8C%E4%BB%A5%E4%BE%BF%E7%89%B9%E5%AE%9A%E5%88%97%E8%8E%B7%E5%BE%97%E7%9B%B8%E5%90%8C%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2.png)
我希望第 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