Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sed substitution of regex string in file

My file has lines with regex such as – =~/Q\d+|0xff0000[0-9a-fA-F]{2}$/

I am trying to replace the regex in above line with – =~/Q\d+|0xff0000[0-9a-fA-F]{2}|0x0{7}1$/

This is what i tried –
sed -i $'s/Q\\d+\|0xff0000\[0\-9a\-fA\-F\]\{2\}\$/Q\\d+\|0xff0000\[0\-9a\-fA\-F\]\{2\}\|0x0\{7\}1\$/g' file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Basically, I am trying to escape – |[]${}-\ characters. But the line in the file remains unchanged. Am i missing something?

Thanks, SO.

>Solution :

sed 's!Q\\d+|0xff0000\[0-9a-fA-F\]{2}!&|0x0{7}1!'
  • Only \ [ ] should be escaped. Escaping \| means treat it as a regex character in this context (if ERE is on, sed -E, the opposite is true).
  • & expands to the matched string.
  • Use ! as the substitutiom delimiter, to avoid confusion with the input data (although / isn’t actually used in the pattern or replacement).
  • This pattern isn’t anchored by a literal $, to do that also, back references can be used: sed 's!\(Q\\d+|0xff0000\[0-9a-fA-F\]{2}\)\(\$\)!\1|0x0{7}1\2!'
  • Back references can also be used for example to anchor the start of the pattern at ~=/ (in the input data).
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading