4

I have several files with two columns : file 1:

1 100
2 103 

file 2

1 200
2 203

and around 600 such files with two columns.

Now, I would like to combine the second column in every file of the first row in the correct sequence to get a single data file like :

100
200
.
.
. (600 lines)

How do I do that?

  • 1
    Are the files named in such a way that a filename globbing pattern would list them in the correct sequence? – Kusalananda Mar 30 at 10:49
8
awk 'FNR==1 {print $2}' file*

This prints the second column ($2) of the first line (FNR==1) for every file whose filename starts with file.

An alternative is to print the first line and then immediately skip to the next file (nextfile is a mawk and GNU awk-specific keyword):

awk '{print $2; nextfile}' file*
1

Best answer has been given above. Tried with below command

for i in file1 file2; do awk 'NR==1{print $2}' $i; done
100
200
  • I'd suggest at least using a wildcard for the for loop, as the OP indicated "around 600 such files" -- so that they don't have to type out each one. Also quote $i as "$i" when you refer to it, otherwise your solution will break on files named, for example: file number 5. – Jeff Schaller Mar 31 at 13:46

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.