How to extract parts of file into separate files in linux using awk or grep or sed commands

awkgrep

I have text file as shown below:

Input file1.txt

.......................
cha21   1       3       5       nar
cha21   2       3       6       piy
cha23   2       3       5       ram
cha23   3       3       3       dam
cha27   5       3       7       pam
................................

And I would like to extract all the 5 columns corresponding to rows of "cha21", "cha23" and "cha27" into 3 different output files(for instance, cha21.txt, cha23.txt, cha27.txt).

output files

cha21.txt

..........
cha21   1       3       5       nar
cha21   2       3       6       piy
......................

cha23.txt

cha23   2       3       5       ram
cha23   3       3       3       dam
...................................

cha27.txt

cha27   5       3       7       pam
...........................

I can do this using grep command 3 times for 3 files…
Is there anyway I can do this all at once, i.e. one command because I need to extract 100 output files.

Best Answer

I would try

awk '{print >> $1 ".txt" ;}' 

where

  • print print the whole line.
  • >> $1 ."txt" write (append) this line to the file indicated by $1, with .txt added.

edit:

in case you have comment lines, lines with dots, etc

try

awk '$1 ~ /cha/ {print >> $1 ".txt" ;}' 

which would only fill file begining with 'cha'.

Related Question