Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace lines in a text file with lines from another file based on matching key fields?

Tags:

bash

unix

sed

awk

input.txt

1,Ram,Fail
2,John,Fail
3,Ron,Success

param.txt (New Input)

1,Sam,Success
2,John,Sucess

Now i want to replace the whole line in input.txt with those present in param.txt . 1st column will act like a primary key.

Output.txt

1,Sam,Success
2,John,Sucess
3,Ron,Success

I tried as

awk 'FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' input.txt param.txt > Output.txt 

But it is merging the file contents.

like image 949
Debaditya Avatar asked Dec 09 '22 23:12

Debaditya


1 Answers

This might work for you (GNU sed):

 sed 's|^\([^,]*,\).*|/^\1/c\\&|' param.txt | sed -f - input.txt

Explanation:

  • Convert param.txt into a sed script using the first field as an address to change the line in the input.txt. s|^\([^,]*,\).*|/^\1/c\\&|
  • Run the script against the input.txt. sed -f - input.txt
like image 121
potong Avatar answered May 15 '23 03:05

potong