Awk

sed 用字元串中的任何隨機單詞替換

  • April 3, 2022

您好,我正在嘗試使用 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 ]

我需要在我跟隨 admin 的隨機使用者之後添加一個名為 sc_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 

我在這裡想念什麼?

跳過已經包含 的行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 ]

引用自:https://unix.stackexchange.com/questions/697451