Jill
Jill

Reputation: 95

SED replace in file

I'm trying to do a simple (I think) search and replace in a file.

Search for the test wrapped between @{...} and replace it with %<...>.

For example:

  1. @{SOMETEXT_A} becomes $<SOMETEXT_A>
  2. @{SOMETEXT_B} becomes $<SOMETEXT_B>
  3. @{SOMETEXT_C} becomes $<SOMETEXT_C>

I have this in sed which matches the search params,

sed -i 's/\@{.\*}/\$<.\*>/g' input.txt

..but doesn't copy the string to the result and instead results in

$<.*>

How do I copy over the regex match from ".*" into the replace string?

Many thanks

Upvotes: 2

Views: 1579

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You can use

sed -i 's/@{\([^{}]*\)}/$<\1>/g' file

See an online demo:

s='@{SOMETEXT_A}  becomes $<SOMETEXT_A>
@{SOMETEXT_B}  becomes $<SOMETEXT_B>
@{SOMETEXT_C}  becomes $<SOMETEXT_C>'
sed 's/@{\([^{}]*\)}/$<\1>/g' <<< "$s"
# => $<SOMETEXT_A>  becomes $<SOMETEXT_A>
#    $<SOMETEXT_B>  becomes $<SOMETEXT_B>
#    $<SOMETEXT_C>  becomes $<SOMETEXT_C>

The @{\([^{}]*\)} regex is a POSIX BRE compliant pattern that matches

  • @{ - a @{ literal string
  • \([^{}]*\) - Capturing group 1 (that is referred to with \1 from the replacement pattern) matching zero or more chars other than curly braces
  • } - a } char.

Upvotes: 3

Related Questions