输出行到与第n列同名的文件

时间:2020-02-03 13:26:18

标签: awk

假设我有这个。

24  Monkey  86  Cat
5743    Fish    6   Dog
abc Monkey  76  Dog
56  Dog 44  Fish
vfg Dog f45 Cat

使用第二列,Id希望将行输出到同名文件,并在需要时创建它。

猴子

24  Monkey  86  Cat
abc Monkey  76  Dog

5743    Fish    6   Dog

56  Dog 44  Fish
vfg Dog f45 Cat

我想处理无限可能的名称,而不是像这样手动指定它们

awk '{ if ( $2=="dog" ) { print $0; } }'

不确定如何使用$ 2作为输出文件名。有可能吗?

2 个答案:

答案 0 :(得分:1)

请您尝试以下。

awk '
{
  close(out_file)
  out_file=$2
  print >> (out_file)
}
' Input_file

答案 1 :(得分:0)

这将完成您的预期。

#!/bin/bash

for animal in $( awk '{ print $2}' animals.txt | sort | sort -u )
do
    awk -v animal="$animal" '$2 == animal{print $0}' animals.txt > "${animal}_list.txt"
done

希望有帮助!