l33tHax0r
l33tHax0r

Reputation: 1721

Appending a column of multiple files to one output file

Say I have three files

file1

1  10.0
2  13.0
3  14.0

file2

1  14.0
2  11.0
3  12.0

file3

1  9.0
2  11.0
3  4.0

And I want to combine the files to one output

outputfile

10.0 14.0 9.0
13.0 12.0 11.0
14.0 12.0 4.0

All files have the same exact number of lines. The second column of each file will be need to be added to the output file

values need to be separated by one space.

I would like to learn how to do this for multiple files, up to 4 in awk or linux terminal.

Upvotes: 0

Views: 109

Answers (5)

putnampp
putnampp

Reputation: 341

join file1 file2 | awk '{print $2 $3}' > outputfile

Join depends upon index column, and spacing.

cat file* | awk '{ if( $1 in x ) { x[$1] = x[$1] " "  $2; } else { x[$1] = $2;}} END{ for( i in x ) { print x[i]; }}' > outputfile

Assumes all input files have the same prefix, and all files are joined according to index column value (ie. $1) (not simply by row index).

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246807

Using bash's process substitutions with the join command:

join <(join file1 file2) file3 | cut -d" " -f2-
10.0 14.0 9.0
13.0 11.0 11.0
14.0 12.0 4.0

With awk, you can write:

awk '
    {result[FNR] = result[FNR] $2 FS} 
    END {for (i=1; i<=FNR; i++) print result[i]}
' file[123]

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203502

Given your new question:

$ paste file1 file2 file3 | awk '{print $2,$4,$6}'
10.0 14.0 9.0
13.0 11.0 11.0
14.0 12.0 4.0

To avoid hard-coding the field numbers in the awk part so it'd work as-is with any output from paste:

$ paste file1 file2 file3 | awk '{for (i=2;i<=NF;i+=2) printf "%s%s",$i,(i<NF?OFS:ORS)}'
10.0 14.0 9.0
13.0 11.0 11.0
14.0 12.0 4.0

Upvotes: 4

karakfa
karakfa

Reputation: 67497

For N number of files in the same format in files list1.txt, list2.txt,...

paste list?.txt | awk '{line=sep=""; for(i=2;i<=NF;i+=2) {line = line sep $i; sep=FS} print line}'

Upvotes: 0

Cody Stevens
Cody Stevens

Reputation: 414

If running linux try using paste command.

paste -d " " file1 file2  > file3

Upvotes: 0

Related Questions