user319869 user319869 - 7 months ago 15
Bash Question

How to use Sed with spaces inside awk

My problem is :
I have file1 :

3119
3359
1359
...


and file2

2222 abc
3359 def <---- this is a match
4444 ghi
...


And I would like to modify each lines where indexes from file 1 are found in file 2 by prefixing the string. Result would be :

2222 abc
3359 PREFIXdef <---- this is a match
4444 ghi
...


I came up with this solution:

sed `cat file1.txt | awk '{print "-e s/"$1"/"$1"PREFIX./"}'`<<<"`cat file2.txt`"


Which give this result :

2222 abc
3359PREFIX def <---- this is a match
4444 ghi
...


How can I add a space before PREFIX and remove the one after ? I have an error
(command not terminated)

Ideally I would add 2 apostrophes around the 's/xx / xx':

sed `cat file1.txt | awk '{print "-e 's/"$1" /"$1" PREFIX./'"}'`<<<"`cat file2.txt`"


But I can't escape the '' !!!

Answer

This awk command can handle that by reaching all 1st columns from first file into an associative array and then checking that against file2:

awk 'FNR==NR{a[$1]; next} $1 in a{$2 = "PREFIX" $2} 1' file1 file2

2222 abc
3359 PREFIXdef
4444 ghi