1

I have multiple files (~15), each with multi column data (tab seperated). For example:

File1

aa1    399     1815
aa2    1908    4064
aa3    4523    5656

File2

bb1    5304317    5305057
bb2    5305057    5305824
bb3    5306871    5307875

etc.

I want to read the 2nd column of each file and print them next to each other, to create a 15 column output. For example:

Output

399     5304317    7526    12455
1908    5305057    8195    14538
4523    5306871    9216    15150

Each column is from different file. Notice the first column of Output is the 2nd column of File1, the sectond column of Output is the 2nd column of File2.

I thought of using paste. But it puts the whole data from each input file. How can this be accomplished?

  • Do all of the files have the same number of lines? – David King Dec 7 '15 at 19:00
  • number of lines and columns will be same. But i want selected column from each file to be joined – Nirvana Dec 7 '15 at 19:05
  • 1
    In the example output, where is that 7526 figure coming from? Can't see it in File1 or File2. – steve Dec 7 '15 at 21:28
  • 1
    @steve: Based on the description of the problem, 7526, 8195, and 9216 come from File3, as 12455, 14538, and 15150 come from File4. – Scott Dec 7 '15 at 21:39
0

For 3 files, each with 3 columns, you could use something like:

pr -m -t -s file1 file2 file3|awk '{printf("%s\t%s\t%s\n",$2,$5,$8)}'

You might also wrapper this with some thing that would count the number of files and fields per file, but this should give you a start.

0

If you're okay not doing it as a one-liner you could do

for file in $(ls File*); do
  awk '{print $2}' < $file > $file.col2
done
pr -m -s *.col2 > merged.txt
rm -f *.col2
0

Perhaps paste could prove suitable after all ?

$ paste <(cut -f2 file1) <(cut -f2 file2) <(cut -f2 file3) <(cut -f2 file4)
399     5304317 7526    12455
1908    5305057 8192    14538
4523    5306871 9216    15150
$

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.