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

StackOverflow https://stackoverflow.com/questions/7442603

  •  20-01-2021
  •  | 
  •  

Вопрос

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

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

So I want to redirect RA records to one file, DI records to another file and SE records to another file. Value in Second column can be anything need not be RA, DI or SE. So based on different values in second column, records need to be redirected to different files..

Это было полезно?

Решение

You could try something like this:

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

Consider that some awk implementations can open a limited number of files at a time. If that's the case you'll need more code, something like this:

[corrected, see comments below]

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

The latter will be far less efficient.

Другие советы

1, using the code tag to make codes easy to read.

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 с атрибуция
Не связан с StackOverflow
scroll top