我正在尝试进行 sed 替换,目前我正在使用两个命令进行替换。我不知道如何将这两个命令组合在一起,以便它一次性正确替换单词。
我在这里的作用是附加sc_admin
到每个有单词的地方admin
。
以下是我能想到的所有单词组合:
access = read : [ admin ], write : [ admin, power ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web ]
access = read : [ admin ]
access = read : [ admin, somerole ], write : [ admin, power ]
所以目前我正在使用 2 个 sed 命令来进行替换
sed -e '/\bsc_admin\b/b' -e '/admin/ s/ *]/, sc_admin ]/' infile
正确替换读取部分中的单词 admin,但不会替换写入部分中的单词 admin。
例如
access = read : [ admin, sc_admin ], write : [ admin, power ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ *, sc_admin ], write : [ admin, wis_master, wis_read_only, wis_web ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole, sc_admin ], write : [ admin, power ]
access = read : [ defadmin, somerole, sc_admin ], write : [ admin, power ]
尽管
sed -e '/\bsc_admin\b/b' -e '/admin/ s/ *] *$/, sc_admin ]/'
命令在写入部分正确附加单词 admin,而对读取部分不执行任何操作。
access = read : [ admin ], write : [ admin, power, sc_admin ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web, sc_admin ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole ], write : [ admin, power, sc_admin ]
access = read : [ defadmin, somerole ], write : [ admin, power ]
因此,目前我正在运行一个命令,然后运行第二个命令来修复文件。有没有一种万无一失的方法来组合命令以便我获得正确的输出?
这是我想要的实际输出:
access = read : [ admin, sc_admin ], write : [ admin, power, sc_admin ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web, sc_admin ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole, sc_admin ], write : [ admin, power, sc_admin ]
答案1
您可以使用以下命令执行以下操作sed
:
$ sed 's/\(\[ admin[^]]*\) /\1, sc_admin /g' file
access = read : [ admin, sc_admin ], write : [ admin, power, sc_admin ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web, sc_admin ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole, sc_admin ], write : [ admin, power, sc_admin ]
\(\[ admin[^]]*\)
捕获字符串 '[ admin<不是 ] 的每个字符和最后一个空格>。为此,我们将捕获括在 , 之间\(...\)
,并用于[^]]*
选择不是 (^
) ']' 的字符。\1, sc_admin
替换为捕获的组 (\1
) 并附加“, sc_admin”。