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
andcut
:If your system does not support process substitution, use this instead:
Using
awk
(thanks @Costas):The special variable
FNR
is the line number of the current input file andNR
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 thea
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.