cms72
cms72

Reputation: 177

How to find and replace in bash that uses a tab-delimited file that contains the original string in column1 and the new string in column 2?

I hope you can help

I have a fileA that contains the following:

(2018-01:0.0000001811,2018-02:0.0000001811)100/100:0.0000076081,(2018-03:0.0000034418,2018-04:0.0000027126)99.1/100:0.0000016303)87.7/95:0.0000003513)92.2/98:0.0000005415)76.1/92:0.0000001772)92.5/98:0.0000005412,((2011-02:0.0000043475,2011-03:0.0000019926)0/97:0.0000000385,(2012-04:0.0000000385,2012-05:0.0000001811)100/100:0.0000048909)98.6/100:0.0000010791)98.5/100:0.0000010848,2012-06:0.0000012543)

And I have a tab delim fileB that contains the following

2018-01  2018-01_2018_A
2018-02  2018-02_2018_B
2018-03  2018-03_2018_C
2018-04  2018-04_2018_D
2011-02  2011-02_2011_A
2011-03  2011-03_2011_B
2012-04  2012-04_2012_A
2012-05  2012-05_2012_B
2012-06  2012-06_2012_C

Basically, I've been trying to use a while loop that searches for all instances of the string in Column1 of file B and replaces it with corresponding string in Column2 to give the following output (2018-01_2018_A:0.0000001811,2018-02_2018_B:0.0000001811)100/100:0.0000076081,(2018-03_2018_C:0.0000034418,2018-04_2018_D:0.0000027126)99.1/100:0.0000016303)87.7/95:0.0000003513)92.2/98:0.0000005415)76.1/92:0.0000001772)92.5/98:0.0000005412,((2011-02_2011_A:0.0000043475,2011-03_2011_B:0.0000019926)0/97:0.0000000385,(2012-04_2012_A:0.0000000385,2012-05_2012_B:0.0000001811)100/100:0.0000048909)98.6/100:0.0000010791)98.5/100:0.0000010848,2012-06_2012_C:0.0000012543)

I've been trying to use

while read a b; do sed -i '' 's/"$a"/"$b"/g' fileA; done < fileB

But it doesn't work. Its not changing anything. I'm using a macOS.

Upvotes: 1

Views: 126

Answers (2)

Shawn
Shawn

Reputation: 52674

Instead of a whole bunch of in-place sed calls, I'd use a single ed instead with all the replacement commands built in a loop and piped to it:

(while read -r a b; do
     printf "g/%s/s/%s/%s/g\n" "$a" "$a" "$b"
 done < fileB;
 echo w) | ed -s fileA

Upvotes: 1

Karthik Radhakrishnan
Karthik Radhakrishnan

Reputation: 944

Just Remove the '' after sed.

while read a b; do sed -i  "s/$a/$b/g" fileA; done < fileB

Result

(2018-01_2018_A:0.0000001811,2018-02_2018_B:0.0000001811)100/100:0.0000076081,(2018-03_2018_C:0.0000034418,2018-04_2018_D:0.0000027126)99.1/100:0.0000016303)87.7/95:0.0000003513)92.2/98:0.0000005415)76.1/92:0.0000001772)92.5/98:0.0000005412,((2011-02_2011_A:0.0000043475,2011-03_2011_B:0.0000019926)0/97:0.0000000385,(2012-04_2012_A:0.0000000385,2012-05_2012_B:0.0000001811)100/100:0.0000048909)98.6/100:0.0000010791)98.5/100:0.0000010848,2012-06_2012_C:0.0000012543)

Upvotes: 1

Related Questions