Qingshan Zhang
Qingshan Zhang

Reputation: 255

use sed to replace string with regular expression line by line

I tried to do some operation on a clex file, the format is like:

name:{id:xxx, ... ...} alias: aaa;
name:{id:yyy, ... ...} alias: bbb;
name:{id:zzz, ... ...} alias: ccc;

What I need to do is to replace the content after name with the ones afer alias. so the result should be:

name:{id:aaa, ... ...} alias: aaa;
name:{id:bbb, ... ...} alias: bbb;
name:{id:ccc, ... ...} alias: ccc;

Can I use sed to complete the operation? I tried to use regular expression but failed. Then I tried to use for loop:

readarray lines < "$file"

for line in "${lines[@]}"; 
do
    ???
done

But was struggled about how to do the replace thing. Can anyone help with this please?

Upvotes: 2

Views: 700

Answers (3)

FredericS
FredericS

Reputation: 413

sed 's/name:{id:[a-z],+(.*)alias: ([a_z]+)/name:{id:\2,\1/alias: \1/

I give you that untested, some control chars might need to be escaped. You can tune the [a-z]+ to match your alias matching.

Upvotes: 0

alestanis
alestanis

Reputation: 21863

You can use sed with something like this:

s/(name:\{id:)[^,]*,(.*)(alias: )([^;]*)/\1\4,\2\3\4/g

Upvotes: 0

Kent
Kent

Reputation: 195039

try this line:

sed -r 's/(name:\{id:)[^,]*(.*alias: )([^;]*);/\1\3\2\3;/' file

with your example data:

kent$  echo "name:{id:xxx, ... ...} alias: aaa;
name:{id:yyy, ... ...} alias: bbb;
name:{id:zzz, ... ...} alias: ccc;"|sed -r 's/(name:\{id:)[^,]*(.*alias: )([^;]*);/\1\3\2\3;/'
name:{id:aaa, ... ...} alias: aaa;
name:{id:bbb, ... ...} alias: bbb;
name:{id:ccc, ... ...} alias: ccc;

Upvotes: 3

Related Questions