简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM