Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed regexp strangeness

Tags:

regex

sed

gnu

trying to replace a string in sed with embedded { and $ and with -E or -r, the { is problematic for me.

according to the docs and many examples I have read, I should only have to escape the { and $ if testing for them. I have whittled it down the simplest case (below)

Probably something I do not understand

I can use my workaround, but this is something that should work with the \{ ?

Given string:

: "${TARGET_PART:=${MMC_PART2}}"

and part=5

I want to replace the ${MMC_PART2}} with ${MMC_PART5}}

The following does not work:

echo ': "${TARGET_PART:=${MMC_PART2}}"'|  sed -r "s/:=\{(MMC_PART).}}/\1$part}}/g"

but the following does work - (replaced "{" with ".")

echo ': "${TARGET_PART:=${MMC_PART2}}"'|  sed -r "s/:=.(MMC_PART).}}/\1$part}}/g"

What am I missing?

like image 362
Floyd Brown Avatar asked Oct 27 '25 13:10

Floyd Brown


1 Answers

Your sed command is syntactically correct but fails to account for the $ in:

: "${TARGET_PART:=${MMC_PART2}}"

The replacement seems wrong too.

The first command should be:

part=5
echo ': "${TARGET_PART:=${MMC_PART2}}"'|  sed -r "s/(:=\\\$\{MMC_PART).(}})/\1$part\2/g"

to output:

: "${TARGET_PART:=${MMC_PART5}}"

Note that inside double-quotes, backslash and dollar should be escaped to avoid alteration by the shell. Inside single-quotes, this is not necessary:

echo ': "${TARGET_PART:=${MMC_PART2}}"'|  sed -r 's/(:=\$\{MMC_PART).(}})/\1'"$part"'\2/g'

Your second command does not perform any substitution for me. Perhaps it was transcribed incorrectly into the question.

like image 165
jhnc Avatar answered Oct 29 '25 06:10

jhnc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!