
假設在 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
因此,要先建立所需的 string ,您可以使用
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=
- 命令開頭的點“來源”輸出。這意味著輸出被解釋為 shell 程式碼。因此變數
$COOKIE
是在目前 shell 中設定的。 - 然後該
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的評論。使用的 shell 是 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