Operating System - HP-UX
1777397 Members
2980 Online
109069 Solutions
New Discussion юеВ

how to combine columns from 2 files into 1 file

 
SOLVED
Go to solution
Charles Li_1
Advisor

how to combine columns from 2 files into 1 file

Hi,
This is what I have:

file1
1 a
2 b
3 c

file 2
1 w1 w2
2 w3 w4
3 w5 w6

How do I change the 2 files above to be this:

file 3
1 a w1 w2
2 b w3 w4
3 c w5 w6

What is the best tool to use?

Thanks.
7 REPLIES 7
Alan Meyer_4
Respected Contributor
Solution

Re: how to combine columns from 2 files into 1 file

file1
a
b
c

file2
w1 w2
w3 w4
w5 w6



# paste file1 file2
a w1 w2
b w3 w4
c w5 w6

" I may not be certified, but I am certifiable... "
Alan Meyer_4
Respected Contributor

Re: how to combine columns from 2 files into 1 file

If you wanted the line #'s heres a scritp for that too

#!/bin/ksh
I=1
cat f1 |awk '{print $1,$2,$3}' |while read Nvar[$I] Avar[$I] ;do
(( I = I + 1 ))
done

I=1
cat f2 |awk '{print $2,$3}' |while read W1[$I] W2[$I] ;do
(( I = I + 1 ))
done

(( MAX = I - 1 ))

I=1
while [ I -le $MAX ] ;do
print ${Nvar[$I]}" "${Avar[$I]}" "${W1[$I]}" "${W2[$I]}
(( I = I + 1 ))
done
" I may not be certified, but I am certifiable... "
Raj D.
Honored Contributor

Re: how to combine columns from 2 files into 1 file

Hi Charles,

Use paste to paste two file column wise..

$ paste file1 file2
a w1 w2
b w3 w4
c w5 w6



or

$ paste file1 file2 > file3

Cheers,
Raj.
" If u think u can , If u think u cannot , - You are always Right . "
Raj D.
Honored Contributor

Re: how to combine columns from 2 files into 1 file

Remember there will be a TAB space between two column, where its merging.

hth,
Raj.
" If u think u can , If u think u cannot , - You are always Right . "
Arunvijai_4
Honored Contributor

Re: how to combine columns from 2 files into 1 file

# paste file1 file2 >file3 will help.

-Arun
"A ship in the harbor is safe, but that is not what ships are built for"
Muthukumar_5
Honored Contributor

Re: how to combine columns from 2 files into 1 file

You can not control column based with paste and pr command. Use awk as,

# awk '{ getline ln< "file1"; print ln,$2,$3; }' file2
1 a w1 w2
2 b w3 w4
3 c w5 w6

hth.
Easy to suggest when don't know about the problem!
Charles Li_1
Advisor

Re: how to combine columns from 2 files into 1 file

.