Mahendra Thapa
Mahendra Thapa

Reputation: 173

how to use loop in awk

I use the following command to extract 2nd column from table1.txt and get output as output1.txt

awk '{ print $2 }' table.txt > output.txt

How to use loop for five files (table.txt, abc.txt, pqr.txt, skt.txt, mkt.txt) to extract 2nd column in respective output files (out_table.txt, out_abc.txt, out_pqr.txt, out_skt.txt, out_mkt.txt) ?

Upvotes: 0

Views: 91

Answers (2)

Kent
Kent

Reputation: 195029

you don't need to write a loop in awk. You could use the build-in variable FILENAME:

awk '{print $2 > "out_"FILENAME".txt"}' table.txt abc.txt pqr.txt skt.txt mkt.txt

Upvotes: 4

Birei
Birei

Reputation: 36252

Use FILENAME variable to use the corresponding output file name to the input one:

awk '{ print $2 > "out_" FILENAME }' *.txt

Upvotes: 3

Related Questions