Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex in sed

Tags:

regex

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 work properly, as it will convert ##FOO## to ${FOO${

like image 757
Dónal Avatar asked Oct 24 '08 18:10

Dónal


5 Answers

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
like image 50
NeronLeVelu Avatar answered Oct 25 '22 09:10

NeronLeVelu


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'
like image 40
postfuturist Avatar answered Nov 10 '22 10:11

postfuturist


  • 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'
like image 2
user24881 Avatar answered Nov 10 '22 11:11

user24881


Use this:

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

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

like image 1
ADEpt Avatar answered Nov 10 '22 09:11

ADEpt


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.

like image 1
Jonathan Leffler Avatar answered Nov 10 '22 10:11

Jonathan Leffler