jp071
jp071

Reputation: 11

Replace a string using sed in Linux

I want to replace following original string by replace string.

original_str="#22=SI_UNIT(*,*,#5,'','metre');"
replace_str="#22=SI_UNIT(*,*,#5,'','millimetre');"
sed -i "s/$original_str/$replace_str/" ./output/modified.txt

I have tried in different ways using 'sed'. However, it is not working. Does anyone have any idea?

The concept #22 is referenced to the other concept later in the same file. Is this the reason?

Please note that it is working fine for following string in the same bash script:

original_str="#103=CARTESIAN_POINT('P3',0.0,0.0,1.0,#72);"
replace_str="#103=CARTESIAN_POINT('P2',10.0,10.0,10.0,#72);"
sed -i "s/$original_str/$replace_str/" ./output/modified.txt

The concept #103 is not used in later concept in the same file.

Thank you.

Upvotes: 1

Views: 151

Answers (2)

tripleee
tripleee

Reputation: 189307

* is a regular expression metacharacter which does not match itself (or only does so coincidentally). You need to escape it in the original_str.

sed -i "s/${original_str//\*/\\*}/$replace_str/" ./output/modified.txt

The $(variable//substr/repl} syntax is Bash-specific. In the general case, you will need to escape any regex specials -- [, \, and . -- which is a bit harder to do in a general way in Bash.

Upvotes: 2

hgiesel
hgiesel

Reputation: 5648

You need to escape characters that have a special meaning in sed, which in this case is *:

original_str='#22=SI_UNIT(\*,\*,#5,'','metre');'
replace_str='#22=SI_UNIT(*,*,#5,'','millimetre');'
sed -i "s/$original_str/$replace_str/" ./output/modified.txt

This will work.

Upvotes: 2

Related Questions