
CLI에서 bash 스크립트를 실행한 후 다음 출력을 받았다고 가정해 보겠습니다. 따라서 이 텍스트는 터미널에 표시됩니다.
POST https://mycompany.com/ COOKIE='BLABLABLABLABLA' HOST='ANYIPADDRESS' FINGERPRINT='sha256:BLABLABLABLA'
의 내용 ( 과
COOKIE
사이의 텍스트만 )을 별도의 파일에 어떻게 저장할 수 있습니까?'
'
또한 언급된 텍스트를 이 외부 파일의 특정 위치에 붙여넣어야 합니다.
이미 존재하는 파일 내용은 다음과 같습니다.
[global] Name = Name of VPN connection [provider_openconnect] Type = OpenConnect Name = Name of VPN connection Host = IP-address Domain = Domain name OpenConnect.Cookie = >>>INSERT CONTENT OF THE COOKIE HERE<<< OpenConnect.ServerCert = sha256:BLABLABLABLA
그게 어떻게 가능합니까?
답변1
이러한 유형의 것은 본질적으로 일반적이지 않지만 접근 방식은 일반적이지만 구체적입니다.
OpenConnect.Cookie =
나는 당신이 라인을 다음으로 바꾸고 싶다고 가정합니다.OpenConnect.Cookie = BLABLABLABLABLA
따라서 먼저 필수 문자열을 생성하려면 다음을 사용할 수 있습니다.
sed -i "s/^OpenConnect.Cookie =.*$/$( command_giving_output | grep 'COOKIE=' | sed "s/COOKIE='//; s/'//g; s/^/OpenConnect.Cookie = /")/" external_filename
여기서는 먼저 필요한 문자열을 생성하기 위해 명령 대체를 사용하고 있습니다.
command_giving_output | grep 'COOKIE=' | sed "s/COOKIE='//; s/'//g; s/^/OpenConnect.Cookie = /"
그런 다음 필수 줄을 이 필수 문자열로 대체합니다.
sed -i "s/^OpenConnect.Cookie =.*$/output from above command substitution /" external_filename
답변2
다음을 사용할 수 있습니다.
. <(command | grep "^COOKIE=")
sed -i "s/\(OpenConnect.Cookie\)\s*=.*/\1 = ""$COOKIE""/" file
어디:
file
질문에 설명된 내용이 포함된 기존 파일입니다.command
터미널에 텍스트를 인쇄하는 명령입니다.grep "^COOKIE="
다음으로 시작하는 줄을 검색합니다.COOKIE=
- 명령 시작 부분의 점은 출력을 "소스"합니다. 이는 출력이 쉘 코드로 해석됨을 의미합니다. 따라서 변수는
$COOKIE
현재 쉘에 설정됩니다. - 그런 다음 명령은
sed
대상 파일의 행을 변수의 내용으로 바꿉니다$COOKIE
.
답변3
어때?
sed -f <(CLI command | sed -n '/COOKIE=\o047/{s//\/OpenConnect.Cookie =\/ s\/= \.*$\/= /; s/.$/\//p;}') file
[global]
Name = Name of VPN connection
[provider_openconnect]
Type = OpenConnect
Name = Name of VPN connection
Host = IP-address
Domain = Domain name
OpenConnect.Cookie = BLABLABLABLABLA
OpenConnect.ServerCert = sha256:BLABLABLABLA
sed
CLI 명령에서 관련 데이터를 추출/마사지하여 즉시 "스크립트 파일"을 생성 하고 두 번째 sed
호출에서 "프로세스 대체"를 사용하여 이 스크립트 파일을 실행합니다.
답변4
이 답변은 다음을 기반으로 합니다.@MSalters님의 댓글입니다. 사용된 쉘은 Bash입니다.
prompt% COOKIE=$(./mycmd | grep -Po "(?<=COOKIE=)'[[:alnum:]]+'" | tr -d \')
prompt% echo "$COOKIE" >/tmp/cookie
prompt% sed -i "s:\(OpenConnect.Cookie =\).*:\1 $COOKIE:" file
대체 솔루션(GNU 사용 expr
)
이 솔루션은 일치하는 결과가 하나만 있는 경우에 작동합니다.
prompt% COOKIE=$(expr "$(./mycmd | grep COOKIE)" : "COOKIE='\([[:alnum:]]\+\)'[[:space:]]*")
prompt% echo "$COOKIE" >/tmp/file
prompt% sed -i "s:\(OpenConnect.Cookie =\).*:\1 $COOKIE:" file