Bash:如何将 CLI 输出的特定行存储到文件中?

Dav*_*ave 7 shell scripting bash shell-script output

  1. 假设我在 CLI 中执行 bash 脚本后收到以下输出(因此此文本将显示在终端中):

    POST https://mycompany.com/
    COOKIE='BLABLABLABLABLA'
    HOST='ANYIPADDRESS'
    FINGERPRINT='sha256:BLABLABLABLA'
    
    Run Code Online (Sandbox Code Playgroud)

    我怎么能存储的内容COOKIE(仅之间的文本'')到一个单独的文件?


  1. 此外,上述文本应粘贴到此外部文件的特定位置。

    已经存在的文件内容如下所示:

    [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
    
    Run Code Online (Sandbox Code Playgroud)

    这怎么可能?

dgf*_*xcv 3

这些类型的事物本质上不是通用的,但是虽然方法是通用的,但是具体的


我假设您想将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
Run Code Online (Sandbox Code Playgroud)

这里我使用命令替换来首先创建所需的字符串

command_giving_output  | grep 'COOKIE=' | sed "s/COOKIE='//; s/'//g; s/^/OpenConnect.Cookie = /"
Run Code Online (Sandbox Code Playgroud)

然后用所需的字符串替换所需的行

sed -i  "s/^OpenConnect.Cookie =.*$/output from above command substitution /" external_filename
Run Code Online (Sandbox Code Playgroud)

  • GNU grep 可以执行 [lookbehind](/sf/ask/87346871/) ,这可以节省嵌套的“sed”。 (2认同)