简体   繁体   中英

How to replace dollar signs before a variable in a string with sed?

I am having problem replacing:

"count: $OFF_COUNT times"

with:

"count: " .. OFF_COUNT .. " times"

I tried:

sed 's/\$\([A-Z0-9_]+\)\b/" .. \1 .. "/g'

But, it had no effect.

Just an unchanged output.

You nearly had the correct command. The only problem is that in basic sed syntax the + is a literal (equivalent to [+] ). Quote from sed 's Appendix A Extended regular expressions :

The only difference between basic and extended regular expressions is in the behavior of a few characters: ? , + , parentheses, and braces ( {} ).
[...]
c\\+ becomes c+ when using extended regular expressions. It matches one or more 'c's.

To enable the usual meaning of + write \\+

sed 's/\$\([A-Z0-9_]\+\)\b/" .. \1 .. "/g'

or use extended sed syntax

sed -E 's/\$([A-Z0-9_]+)\b/" .. \1 .. "/g'

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