我有一个包含30列(重复ID、名称和位置)的文件,我需要及时提取3列并将它们每次放入一个新文件中:
ID Name Place ID Name Place ID Name Place ID Name place ...
19 john NY 23 Key NY 22 Tom Ny 24 Jeff NY....
20 Jen NY 22 Jill NY 22 Ki LA 34 Jack Roh ....所以我会有10个这样的文件-
Output1.txt
ID Name Place
19 john NY
20 Jen NY Output2.txt
ID Name Place
23 Key NY
22 Jill NY 还有8个像这样的文件。我可以打印像awk '{print $1,$2,$3}' Input.txt > Output1.txt这样的列,但是对于10个文件来说可能太麻烦了。有我能让它更快吗?
谢谢!
发布于 2016-09-28 18:32:43
$ awk '{for (i=1;i<=NF;i+=3) {print $i,$(i+1),$(i+2) > ("output" ((i+2)/3) ".txt")}}' file.txt
# output1.txt
ID Name Place
19 john NY
20 Jen NY
# output2.txt
ID Name Place
23 Key NY
22 Jill NY
# output3.txt
ID Name Place
22 Tom Ny
22 Ki LA
# output4.txt
ID Name place
24 Jeff NY
34 Jack Roh发布于 2016-09-28 18:41:55
从这个美妙的Ed Morton's answer上稍微调整了一下,
awk -v d=3 '{sfx=0; for(i=1;i<=NF;i+=d) {str=fs=""; for(j=i;j<i+d;j++) \
{str = str fs $j; fs=" "}; print str > ("output_file_" ++sfx)} }' file会根据你的要求进行文件分割。
请记住,awk变量d定义了要拆分的列数,在您的示例中为3列。
发布于 2016-09-28 19:23:58
$ awk '{for(i=0;i<=NF/3-1;i++) print $(i*3+1), $(i*3+2), $(i*3+3)>i+1".txt"}' file
$ cat 1.txt
ID Name Place
19 john NY
20 Jen NYhttps://stackoverflow.com/questions/39754839
复制相似问题