Woerrie Woerrie - 4 months ago 7
Bash Question

Replacing a substring in certain lines of file A by string in file B

I have 2 files at the moment, file A and file B. Certain lines in file A contain a substring of some line in file B. I would like to replace these substrings with the corresponding string in file B.

Example of file A:

@Name_1
foobar
info_for_foobar
evenmoreinfo_for_foobar
@Name_2
foobar2
info_for_foobar2
evenmoreinfo_for_foobar2


Example of file B:

@Name_1_Date_Place
@Name_2_Date_Place


The desired output I would like:

@Name_1_Date_Place
foobar
info_for_foobar
evenmoreinfo_for_foobar
@Name_2_Date_Place
foobar2
info_for_foobar2
evenmoreinfo_for_foobar2


What I have so far:

I was able to get the order of the names in File B corresponding to those in File A. So I was thinking to use a while loop here which goes through every line of file B, and then finds and replaces the corresponding substring in file A with that line, however I'm not sure how to put this into a bash script.

The code I have so far is, but which is not giving a desired output:

grep '@' fileA.txt > fileAname.txt

while read line
do
replace="$(grep '$line' fileB.txt)"
sed -i 's/'"$line"'/'"$replace"'/g' fileA.txt
done < fileAname.txt


Anybody has an idea?

Thanks in advance!

Answer

You can do it with this script:

awk 'NR==FNR {str[i]=$0;i++;next;} $1~"^@" {for (i in str) {if(match(str[i],$1)){print str[i];next;}}} {print $0}' B.txt  A.txt
Comments