Extracting columns from multiple files with awk

hi everyone!

I'd like to extract a single column from 5 different files and put them together in an output file. I saw a similar question for 2 input files, and the line of code workd very well, the code is:

awk 'NR==FNR{a[NR]=$2; next} {print a[FNR], $2}' file1 file2

I added the file3, file4 and file5 at the end, but it doesn't work. Does anyone know what do I have to do?

Thanks in advance.
Joc

u can make use of cut command like

cut -f3 file1.txt file2.txt file3.txt file4.txt

Will be the same column from each file?

yes, the same column

---------- Post updated at 09:40 AM ---------- Previous update was at 09:33 AM ----------

This works but it puts one column below the other... is it possible to put them side by side?
thanks

with the help of cut and paste you can get the result

$cut -f3 file7.txt >temp1.txt
$cut -f3 file8.txt >temp2.txt
$paste temp1.txt temp2.txt >file.txt
1 Like

that works, thank you

Try this:

awk '{printf s $3;s=FS}END{print ""}' file1 file2 file3 file4

awk '{printf s $3; s=F}END{print ""}' dom1of5.txt dom2of5.txt dom3of5.txt dom4of5.txt
awk: run time error: not enough arguments passed to printf("Oil[%]")
FILENAME="dom1of5.txt" FNR=1 NR=1
Oil[

---------- Post updated at 11:27 AM ---------- Previous update was at 11:19 AM ----------

awk '{printf s $3; s=FS}END{print ""}' dom1of5.txt dom2of5.txt dom3of5.txt dom4of5.txt
awk: run time error: not enough arguments passed to printf("Oil[%]")
FILENAME="dom1of5.txt" FNR=1 NR=1
Oil[

---------- Post updated at 11:27 AM ---------- Previous update was at 11:27 AM ----------

I'm not sure if I typed it correctly:
awk '{printf s $3; s=FS}END{print ""}' dom1of5.txt dom2of5.txt dom3of5.txt dom4of5.txt
awk: run time error: not enough arguments passed to printf("Oil[%]")
FILENAME="dom1of5.txt" FNR=1 NR=1
Oil[

Sorry, printf doesn't work like that with some awk versions, try this:

awk '{printf("%s%s", s, $3);s=FS}END{print ""}' dom1of5.txt dom2of5.txt dom3of5.txt dom4of5.txt

You should use FNR (not NR) to control multiple files.

awk '{a[FNR]=a[FNR] FS $2;t=(FNR>T)?FNR:t}END {for (i=1;i<=t;i++) print a}'  file1 file2 file3 file4
1 Like

Could you please elaborate the code, some where i missed the logic.:confused: