-1

In a file x, a line containing 4*4 4*1 4*4 4*0 is to be replaced by 4*4 4*1 3*4 1*4 4*0 which is in file y. I'm using the following code:

#!/bin/bash
old=`grep "4*4" x`;
new=`grep "4*4" y`;
sed -i "s/${old}/${new}/g" x

but it yields no change at all in x. I'm a novice and this might be a silly question for this site but I'm unable to replace this expression with multiple special characters with another expression.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
srikrishna
  • 23
  • 5

1 Answers1

0

Welcome to stackOverflow - An awesome platform for developers
If you stick around, you will also find it very rewarding.

Now to your question.

* is a special character for sed when it is included in pattern to match. More info here.
Thus, we need to escape it with a \.

You can use something like old=$(echo "${old}" | sed -r 's/[*]/\\*/g') to do so for each * inside variable old.

  • echo "${old}" | feeds the value of variable old to sed.
  • Let me write the sed command in an expanded form: sed -r 's/ [*] / \\* /g'
    • -r because we are using regex in pattern to match.
    • [*] is the regex and also the pattern to match. Info
    • \\* is the replacement string - The first \ is escaping the second \ and * is being treated as a normal character.
  • $( ) has been used to assign the final output to variable old.


Here is the modified script:

#!/bin/bash

# Read the strings
old=`grep "4*4" x`;
new=`grep "4*4" y`;

# Escape * i.e. add \ before it - As * is a special character for sed
old=$(echo "${old}" | sed -r 's/[*]/\\*/g')

# Replace
sed -i "s/${old}/${new}/g" x
Vinay Vissh
  • 457
  • 2
  • 9
  • 12
  • Since this is Bash, we can just use parameter substition: `${old//\*/\\*}`. See my (related) [answer to *sed replace with variable with multiple lines*](/a/39269241). – Toby Speight Oct 04 '18 at 12:22
  • @TobySpeight The `sed` version is much more readable for a web + mobile dev like me. I agree that bash's parameter substitution will always be faster than any other method. Matter of which trade off you want to take – Vinay Vissh Oct 04 '18 at 15:23
  • Hmm... To the person who down voted my answer: Can you please tell me the reason? So that I can improve it. – Vinay Vissh Oct 08 '18 at 07:53