简体   繁体   中英

regex in sed

I need to use sed to convert all occurences of ##XXX## to ${XXX}. X could be any alphabetic character or '_'. I know that I need to use something like:

's/##/\${/g'

But of course that won't properly, as it will convert ##FOO## to ${FOO${

Any takers? - Don

Here's a shot at a better replacement regex:

's/##\([a-zA-Z_]\+\)##/${\1}/g'

Or if you assume exactly three characters :

's/##\([a-zA-Z_]\{3\}\)##/${\1}/g'
  • Encapsulate the alpha and '_' within '\\(' and '\\)' and then in the right side reference that with '\\1'.
  • '+' to match one or more alpha and '_' (in case you see ####).
  • Add the 'g' option to the end to replace all matches (which I'm guessing is what you want to do in this case).
's/##\([a-zA-Z_]\+\)##/${\1}/g'

Use this:

s/##\([^#]*\)##/${\1}/

BTW, there is no need to escape $ in the right side of the "s" operator.

sed 's/##\([a-zA-Z_][a-zA-Z_][a-zA-Z_]\)##/${\1}/'

The \\(...\\) remembers...and is referenced as \\1 in the expansion. Use single quotes to save your sanity.

As noted in the comments below this, this can also be contracted to:

sed 's/##\([a-zA-Z_]\{3\}\)##/${\1}/'

This answer assumes that the example wanted exactly three characters matched. There are multiple variations depending on what is in between the hash marks. The key part is remembering part of the matched string.

echo "##foo##" | sed 's/##/${/;s//}/'
  • s change only 1 occurence by default
  • s// take last search pattern used so second s take also ## and only the second occurence still exist

sed's /([^ az] [^ AZ] [^ 0-9] *)/(&)/ pg

echo '##XXX##' | sed "s/^##([^#]*)/##${\\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