1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes you're right, but I just realized, that you can escape #, which I find very interesting.
As I wrote, the later code (replace) is working. I want to replace first code. That is 'metre' to 'millimetre'. Additionally, I have tried with '\'. It does not work for the issue.
2

* 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.