使用sed将文本替换为2个以“ /”分隔的串联变量

时间:2018-08-21 21:49:57

标签: bash variables sed concatenation

我有一个包含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

一如既往,在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我想你想做这样的事情

$ 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的{​​{1}}分隔符(此处选择了~),因为您的数据中可能包含分隔符。

答案 1 :(得分:0)

所以看起来好像有2个问题。我在“ \ $ script_path / cef.conf”末尾逃避了变量的使用,并更改了sed的Dilemeter,使它能够正常工作。

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

再次感谢所有。