こんにちは、私は文字列の後にランダムな文字列が続くファイルを置き換えるために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
私がここで何を見逃しているのでしょうか?
答え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 ]