4

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.

  • 3
    Are those dots present in the original file? Because the solutions below would have a subtle effect if run on a file like that. – kos Jun 12 '15 at 10:57
6

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

  • This creates a file named ..................................txt on my computer. – mikeserv Jun 12 '15 at 18:40
6

It is easy with awk:

awk '{print $0 >> $1".txt"}' file1.txt
  • 4
    Why print $0 and not just print? Are there versions of awk that need the explicit $0 ? – terdon Jun 12 '15 at 10:43
  • This also creates a file named w/ a lot of dots on my machine. That can't be the expected behavior - what am I doing wrong? – mikeserv Jun 12 '15 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.