Sed 替换为字符串中的任意随机单词

Sed 替换为字符串中的任意随机单词

您好,我正在尝试使用 sed 对文件进行替换,其中字符串后跟任何随机字符串。我的原始文件如下所示。

access = read : [ * ], write : [ admin, sc_admin ]
access = read : [ * ], write : [ admin, myuser ]
access = read : [ * ], write : [ admin ]
access = read : [ * ], write : [ admin, randomuser ]
access = read : [ * ], write : [ admin, randomuser, somedude ]
access = read : [ * ], write : [ admin, justarandomuser, somedude, anotherdude ]
access = read : [ * ], write : [ admin, another_random_user ]

我需要在我的随机用户后面添加一个名为 sc_admin 的字符串,该用户遵循 admin,以便它看起来像这样

access = read : [ * ], write : [ admin, sc_admin ]
access = read : [ * ], write : [ admin, myuser, sc_admin ]
access = read : [ * ], write : [ admin ]
access = read : [ * ], write : [ admin, randomuser, sc_admin ]
access = read : [ * ], write : [ admin, randomuser, somedude, sc_admin ]
access = read : [ * ], write : [ admin, justarandomuser, somedude, anotherdude, sc_admin ]
access = read : [ * ], write : [ admin, another_random_user, sc_admin ]

我正在尝试运行以下 sed 命令,但它没有执行任何操作。

sed -r "s/\[\ admin\,\ \w+\ \]/\[\ admin\,\ \w+\,\ sc\_admin\ \]/g" local.meta 

我在这里缺少什么?

答案1

跳过已包含 的行sc_admin,然后仅替换包含以下内容的行admin,

sed -e '/\bsc_admin\b/b' -e '/admin,/ s/ *] *$/, sc_admin ]/' infile

输出:

access = read : [ * ], write : [ admin, sc_admin ]
access = read : [ * ], write : [ admin, myuser, sc_admin ]
access = read : [ * ], write : [ admin ]
access = read : [ * ], write : [ admin, randomuser, sc_admin ]
access = read : [ * ], write : [ admin, randomuser, somedude, sc_admin ]
access = read : [ * ], write : [ admin, justarandomuser, somedude, anotherdude, sc_admin ]
access = read : [ * ], write : [ admin, another_random_user, sc_admin ]

答案2

使用sed

$ sed '/sc_admin\>/!s/\[ admin,.*[a-z]/&, sc_admin/' input_file
access = read : [ * ], write : [ admin, sc_admin ]
access = read : [ * ], write : [ admin, myuser, sc_admin ]
access = read : [ * ], write : [ admin ]
access = read : [ * ], write : [ admin, randomuser, sc_admin ]
access = read : [ * ], write : [ admin, randomuser, somedude, sc_admin ]
access = read : [ * ], write : [ admin, justarandomuser, somedude, anotherdude, sc_admin ]
access = read : [ * ], write : [ admin, another_random_user, sc_admin ]

答案3

awk '!/sc_admin/ && /admin,/{gsub(/\]$/,",scadmin ]",$0)}1' filename

输出

access = read : [ * ], write : [ admin, sc_admin ]
access = read : [ * ], write : [ admin, myuser ,scadmin ]
access = read : [ * ], write : [ admin ]
access = read : [ * ], write : [ admin, randomuser ,scadmin ]
access = read : [ * ], write : [ admin, randomuser, somedude ,scadmin ]
access = read : [ * ], write : [ admin, justarandomuser, somedude, anotherdude ,scadmin ]
access = read : [ * ], write : [ admin, another_random_user ,scadmin ]

相关内容