Take the first column from 2 files and write it to a 3rd file

text processing

Suppose I have 2 Files, ABC.txt & PQR.txt with the data shown below as an example:

ABC.txt:

ABC DEF

PQR.txt:

PQR XYZ

I want to grep column 1 from both files and write into a third text file. How can it be done?

My expected output is (output.txt):

ABC PQR

Best Answer

Here are a couple of ways:

  • Using paste and cut :

    $ paste -d ' ' <(cut -d' ' -f 1 ABC.txt ) <(cut -d' ' -f 1 PQR.txt ) > output.txt
    ABC PQR
    

    If your system does not support process substitution, use this instead:

    $ cut -d' ' -f 1 ABC.txt > /tmp/aa; cut -d' ' -f 1 PQR.txt > /tmp/bb; paste -d ' ' /tmp/aa /tmp/bb
    
  • Using awk (thanks @Costas):

    awk 'FNR==NR{a[FNR]=$1; next}{print a[FNR],$1}' ABC.txt PQR.txt > output.txt
    

    The special variable FNR is the line number of the current input file and NR is the line number of the input in general, whatever file it came from. The two are equal only while the first input file is being read. So, the first fields of the first file are saved in the a array (a[FNR]=$1) whose keys are line numbers and whose values are the 1st fields. Then, when the second file is reached, we print the value corresponding to its line number (a[NR]) and the current line's 1st field.

Related Question