0

I have a file where I want to extract two columns and add at a specific location to another file that is already full of columns.

Could I cat file 1 and make it a variable and then cat file 2 and make it a variable and then combine variables with export and awk? Someone helped me before with single lines of text in this manner, but I don't know if it applies to whole files.

example:

Input file 1

Group F3D0 F3D1 F3D9 F3D     
Otu01 1627 1935 8335 241

Input file 2

oi1 oi2    
lk8 po8    

Output file

oi1 oi2 Group F3D0 F3D1 F3D9 F3D     
lk8 po8 Otu01 1627 1935 8335 241
  • 4
    It seems like you don't need any more that paste -d ' ' file2 file1 in this case – steeldriver May 28 '16 at 1:22
  • fair enough, but what if the addition of file 2 needed to go to a specific column location (rather than just the start of file 1), how do you code for that? – Giles May 28 '16 at 13:42
1

In the case you show, all you really need is

paste -d ' ' file2 file1

You an do pretty much whatever you want order-wise using cut and paste (and some shell process substitution) e.g. to output the first two columns of file1 followed by the second column of file2 followed by the remainder of file1 and finally the first column of file2 you could do

paste -d ' ' <(cut -d ' ' -f 1,2 file1) <(cut -d ' ' -f 2 file2) <(cut -d ' ' -f 3- file1) <(cut -d ' ' -f 1 file2)

Or (perhaps more efficiently) you could paste the two files together as-is and pipe the result to awk to select specific columns in a specific order:

paste -d ' ' file1 file2 | awk '{print $1, $2, $NF, $3, $4, $5, $(NF-1)}'

or (if you prefer), with perl

paste -d ' ' file1 file2 | 
  perl -alne 'print join " ", @F[0,1],@F[6],@F[2..4],@F[5]'
  • sweet answer thanks, can't even begin to tell you how handy that explanation is for me in understanding and improving my text processing. – Giles May 28 '16 at 14:04

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.