假设我有这个。
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作为输出文件名。有可能吗?
答案 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
希望有帮助!