Home > OS >  sed replace regex match group
sed replace regex match group

Time:06-22

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\"

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

CodePudding user response:

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

CodePudding user response:

With your shown example. I switched from s/// to s|||.

sed 's|".*/|"ooooo/|' file

Output:

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

BLBLBL
BL2BL2BL
  • Related