簡體   English   中英

如何使用nawk / awk根據文件中某一列中的值將記錄重定向到不同的輸出文件?

[英]How to redirect records to different output files based on a value in one of the columns in a file using nawk/awk?

如何使用nawk / awk根據文件中某一列中的值將記錄重定向到不同的輸出文件?

chethan RA
Ramesh  RA
Sachin  RA
Gundaa  DI
dravid  DI
Suresh  SE

所以我想將RA記錄重定向到一個文件,將DI記錄重定向到另一個文件,將SE記錄重定向到另一個文件。 第二列中的值可以是不需要為RA,DI或SE的任何值。 因此,根據第二列中的不同值,需要將記錄重定向到不同的文件。

您可以嘗試這樣的事情:

4.1.10(4)-release$ cat infile 
chethan RA 
Ramesh RA 
Sachin RA 
Gundaa DI 
dravid DI 
Suresh SE
4.1.10(4)-release$ awk '{
>   f = $2 ".txt"
>   print > f
>   }' infile
4.1.10(4)-release$ head *txt
==> DI.txt <==
Gundaa DI 
dravid DI 

==> RA.txt <==
chethan RA 
Ramesh RA 
Sachin RA 

==> SE.txt <==
Suresh SE

考慮到某些awk實現一次只能打開有限數量的文件。 如果是這種情況,您將需要更多代碼,例如:

[更正,請參閱下面的評論]

awk '{
  if (f) close(f)
  f = $2 ".txt"
  print >> f
  }' infile

后者的效率將大大降低。

1,使用代碼標簽使代碼易於閱讀。

kent$  cat a
chethan RA 
Ramesh RA 
Sachin RA 
Gundaa DI 
dravid DI 
Suresh SE


kent$  awk '{print >> $2".txt"}' a


kent$  l
total 16K
-rw-r--r-- 1 kent kent 66 2011-09-16 11:39 a
-rw-r--r-- 1 kent kent 22 2011-09-16 11:42 DI.txt
-rw-r--r-- 1 kent kent 34 2011-09-16 11:42 RA.txt
-rw-r--r-- 1 kent kent 10 2011-09-16 11:42 SE.txt

kent$  head *.txt
==> DI.txt <==
Gundaa DI 
dravid DI 

==> RA.txt <==
chethan RA 
Ramesh RA 
Sachin RA 

==> SE.txt <==
Suresh SE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM