Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
hi,
I've 2 files, file1.txt and file2.txtfile1.txt has variables like
1111, 2222, 3333
4444,5555,6666
7777,8888,9999file2.txt has values like
aaaa,bbbb,cccc
dddd,eeee,ffff,
gggg,hhhh,iiiiI wan to replace the columns and form a output file like
1111, bbbb, 3333
4444,eeee,6666
7777,hhhh,9999Can you please help me.
Thanks
Hi,
I'm trying to replace a column in a comma seperated file with a column in another file using sed/awk. Can anyone help me.Thanks
Siva

Here's one solution, and I am assuming that your two input files have the same number of lines and are sorted as desired.
The pr command will join the lines from each file side by side, then awk will print the desired columns. On some platforms, instead of pr -m (merge), it may be pr -j (join).
This code does not concern itself with spaces. Columns are delimited by commas, and if you happen to have spaces in your data, they will remain. Or awk can take those out with a gsub command.
pr -tm -s"," file?.txt|
awk -F, '{OFS=",";print $1,$5,$3}'
1111,bbbb, 3333
4444,eeee,6666
7777,hhhh,9999

I was using a wildcard on my testing. That first line should explicitly list your two input files:
pr -tm -s"," file1.txt file2.txt |

Great, pr -tm -s"," file1.txt file2.txt> file3 worked.
Thanks a lot Jim.Siva
Hi,
I'm trying to replace a column in a comma seperated file with a column in another file using sed/awk. Can anyone help me.Thanks
Siva

Another way is to place the second column of file 2 into an array, and read file 1 and replace the second column with what's in the array:
#!/bin/ksh
cnt=0
while IFS="," read c1 c2 c3
do
rr[$cnt]=$c2
cnt=$((cnt+1))
done < file2cnt=0
while IFS="," read c1 c2 c3
do
printf "%s,%s,%s\n" "$c1" ${rr[$cnt]} "$c3"
cnt=$((cnt+1))
done < file1

Great, Thanks Nail.
Siva
Hi,
I'm trying to replace a column in a comma seperated file with a column in another file using sed/awk. Can anyone help me.Thanks
Siva

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |