1

I have multiple text files, and I wish to extract specific columns from these files and save them to *_2.txt files.

awk '{print $(NF-3), $5}' *.txt > *_2.txt 

But this command is not working. How can I achieve this batch column extraction using awk?

Input:

a.txt
aaa bbb ccc          109.6136     93.1900      1.0000    269.7332  35703.1790
ddd eee fff            48.8760     34.2100      1.0000    215.0926  35918.2717
ggg hhh iii                     17.3588    -65.4900      0.7000  14008.0228  49926.2945
...

b.txt 
qq ss rr         105     71.6239     68.1500      3.0000      1.3408   4329.5373
aa bb nn         110    271.3443    231.4200     10.0000     15.9395   4345.4768
rr uu ii         115    338.2163    415.6700     25.0000      9.5985   4355.0753
zz xx yy         120    536.0957    584.7900     50.0000      0.9485   4356.0238
...

Target output:

a_2.txt
109.6136     93.1900      1.0000
 48.8760     34.2100      1.0000
 17.3588    -65.4900      0.7000
...

b_2.txt
105     71.6239     68.1500
110    271.3443    231.4200
115    338.2163    415.6700
120    536.0957    584.7900
...

I wish to extract specific columns from each text file and save them to each text file with _2 added to the name. Target column is $(NF-5), $(NF-4), $(NF-3)

1
  • According to what you wrote input is a single file. Why are you using * then? Jan 9, 2021 at 19:01

1 Answer 1

2

You have to do this within AWK script like that:

awk 'FNR == 1 { sub(/\.txt$/, "_2.txt", FILENAME) }  { print $(NF-3), $5 > FILENAME }' *.txt
4
  • It didn't crate a single _2.txt file with target column, but it created multiple _2.txt, _2_2.txt, _2_2_2.txt.... files, and each file contains single lines.
    – exsonic01
    Jan 9, 2021 at 18:53
  • Yes, I thought this is what you want. If this is not what you want update your question and post sample input and desired output. Jan 9, 2021 at 18:54
  • I added example
    – exsonic01
    Jan 9, 2021 at 19:00
  • @exsonic01: see updated answer Jan 9, 2021 at 19:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .