Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Read string from one file and replace in other file

Tags:

shell

awk

My requirement is to read the string from input file and replace all its occurrences with replaced string into output file. Example:

$ cat input
BOB_XYZ  "JOB.ABC"
ROB_LOLA  "TOT.XYZ"
$ cat output
{
BOB_XYZ is a BOB_XYZ
I am BOB_XYZ
}

Here, I need to replace "BOB_XYZ" with "JOB.ABC" from output file. I mean expected output as

$ cat output
{
"JOB.ABC" is a "JOB.ABC"
I am "JOB.ABC"
} 

Please let me know, how we do this

like image 241
user2803710 Avatar asked Mar 14 '26 01:03

user2803710


1 Answers

Using awk, here is one way to do it. Loop through input and output files, collecting the "variables" from input into an array a and applying field-by-field replacements on output

awk 'NR == FNR{a[$1]=$2; next};
    {for (i=1; i<=NF; ++i) if ($i in a) $i=a[$i]; print}' input output
like image 110
iruvar Avatar answered Mar 15 '26 13:03

iruvar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!