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 replace regex match group

I’ve a file:

import "aaaa/bbbb.ccc";
import "dddd/eeee.ccc";
import "fffff/ggg/hhhh.ccc";

BLBLBL
BL2BL2BL

And I want to replace the path of the import like this:

import "ooooo/bbbb.ccc";
import "ooooo/eeee.ccc";
import "ooooo/hhhh.ccc";

BLBLBL
BL2BL2BL

I’ve my regex with a match group of the part I want to replace:
import \"([a-zA-Z]+\/|[a-zA-Z]+\/+[a-zA-Z]+\/)[a-zA-Z]+\.ccc\"

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

But I don’t know how to use it with sed to replace it with ooooo/

>Solution :

You can use

sed -E 's,^(import ").*/,\1ooooo/,' file > newfile

Details:

  • -E – enabling POSIX ERE syntax
  • ^(import ").*/ – matches start of string (^), import ", and then one or more chars until the last /
  • \1ooooo – replaes with Group 1 value plus ooooo.

The , char is used as a regex delimiter chars, so no need to escape / chars.

See the online demo:

#!/bin/bash
s='import "aaaa/bbbb.ccc";
import "dddd/eeee.ccc";
import "fffff/ggg/hhhh.ccc";

BLBLBL
BL2BL2BL'
sed -E 's,^(import ").*/,\1ooooo/,' <<< "$s"

Output:

import "ooooo/bbbb.ccc";
import "ooooo/eeee.ccc";
import "ooooo/hhhh.ccc";

BLBLBL
BL2BL2BL
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