안녕하세요, 저는 문자열 뒤에 임의의 문자열이 오는 파일을 대체하기 위해 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 ]