Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replacing columns of one file with that of another file 1

Status
Not open for further replies.

hill007

Technical User
Mar 9, 2004
60
US
I have a file1 which I want to replace last 2 columns of the file with 2 columns from another file 2.

For example:
File 1

A B C D E F
1 2 3 4 5 6
A B C D I J

File 2
a b
c d
e f

The final output would be:

A B C D a b
1 2 3 4 c d
A B C D e f

Any help appreciated.
 
Something like this ?
awk '
FNR==NR{a[FNR]=$0;next}
{print $1,$2,$3,$4,a[FNR]}
' File2 File1

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Not tested

awk -f hill.awk file2 file1

#hill.awk
NR==FNR(a1[NR]=$(NF-1);a2[NR]=$NF;next}
{$(NF-1)=a1[FNR];$NF=a2[FNR];print}

CaKiwi
 
Hi PHV,

Actually I have 500 columns in file 1 and want to replace last 4 columns with file 2.
Writing out the full print statement for 496 columns is laborious. Is there any otherway.
Thanks.
 
nawk -f hill.awk file2 file1

here's the hill.awk:

Code:
FNR == NR { f2[FNR] = $(NF-1) OFS $NF; next }
{
   NF -= 2; $1=$1
   print $0, f2[FNR];
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Hi vgersh99,

If I want to replace contents of file2 with last 4 columns of file 1. What I need to change in your code? I could'nt follow the code.
Thanks.
 
Code:
FNR == NR { f2[FNR] = $(NF-3) OFS $(NF-2) OFS $(NF-1) OFS $NF; next }
{
   NF -= 4; $1=$1
   print $0, f2[FNR];
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thanks vgersh99. Actually I tried in awk95 and it worked.

Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top