Search code examples
unixawksolarisnawk

How to redirect records to different output files based on a value in one of the columns in a file using 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?..

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..


Solution

  • 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.