使用sed逐行替换正则表达式字符串

时间:2022-03-23 16:49:55

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

我试着对一个clex文件做一些操作,格式是:

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:

我可以用sed完成手术吗?我试图使用正则表达式,但失败了。然后我尝试用for循环:

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?

但是在如何做替换的问题上很纠结。有人能帮忙吗?

3 个解决方案

#1


3  

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;

#2


0  

You can use sed with something like this:

您可以将sed与以下内容一起使用:

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

#3


0  

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

sed的s /名称:{ id:[a - z]+(. *)别名:([a_z]+)/名称:{ id:\ 2 \ 1 /别名:\ 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.

我给你那个未经测试的,一些控制符号可能需要被转义。您可以调整[a-z]+以匹配您的别名匹配。

#1


3  

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;

#2


0  

You can use sed with something like this:

您可以将sed与以下内容一起使用:

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

#3


0  

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

sed的s /名称:{ id:[a - z]+(. *)别名:([a_z]+)/名称:{ id:\ 2 \ 1 /别名:\ 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.

我给你那个未经测试的,一些控制符号可能需要被转义。您可以调整[a-z]+以匹配您的别名匹配。