【问题标题】:Using sed to replace text with 2 concatenated variables separated by "/"使用 sed 用“/”分隔的 2 个连接变量替换文本
【发布时间】:2019-01-28 03:25:03
【问题描述】:

我有一个包含 2 个变量的脚本。其中一个变量是目录路径,另一个是用户输入变量。一旦用户输入变量,在本例中为证书名称,我使用 sed 将 xxxxx 的文本替换为由 / 分隔的 script_path 和 certfile 变量。

在编程方面还是新手,但除了以下问题之外,我已经设法让我的脚本正常工作。我尝试将变量转义为“/”,但似乎没有任何效果。

我还尝试更改 sed 也使用的分隔符,但没有成功。我确实搜索了很多,但没有找到使用“/”和连接变量的任何具体内容,所以如果这已经解决,请提前道歉。

#!/bin/bash
script_path=/opt/ceflog

read -p 'Enter the name of the certificate file: ' certfile
sed -e "s/pkcs12_file = xxxxxx/pkcs12_file = $script_path/$certfile/g" \$script_path/cef.conf

应该如下所示。

pkcs12_file = /opt/ceflog/192.168.1.1_1.pkcs12

一如既往地提前感谢您的帮助。

【问题讨论】:

  • 抱歉,有什么问题吗?这里有很多事情要做,所以我建议在继续之前先发送MCVE

标签: bash variables sed concatenation


【解决方案1】:

所以看起来有 2 个问题。我逃脱了对“\$script_path/cef.conf”末尾变量的使用,并更改了 sed 的 dilemeter,我能够让它工作。

sed -e "s|pkcs12_file = xxxxxx|pkcs12_file = $script_path/$certfile|g" $script_path/cef.conf

再次感谢大家。

【讨论】:

    【解决方案2】:

    我猜你想做这样的事情

    $ path='/opt/ceflog'; cert='192.168.1.1_1.pkcs12'; 
    $ echo pkcs12_file = xxxxxx/pkcs12_file | 
      sed -E 's~(pkcs12_file =) (xxxxxx/pkcs12_file)~\1 '"${path}/${cert}"'~'
    
    
    pkcs12_file = /opt/ceflog/192.168.1.1_1.pkcs12
    

    使用与默认分隔符 (/) 不同的 sed 分隔符(这里我选择了 ~),因为您的数据中可能包含它。

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 2017-12-20
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2020-09-29
      • 2016-10-06
      • 2021-12-11
      • 2011-11-25
      相关资源
      最近更新 更多