如何使用sed在字符串匹配后附加带有美元符号的变量?

时间:2016-09-09 14:16:00

标签: linux bash perl awk sed

我有一个带有美元符号的变量:

ipvar_definitions="
var SSH_SERVERS \$HOME_NET
var FTP_SERVERS \$HOME_NET
var SIP_SERVERS \$HOME_NET
"

我想在匹配后使用sed或perl或我可以使用的任何内容附加此变量的值。

使用以下代码尝试使用sed时:

sed   "/var SNMP_SERVERS/a ${ipvar_definitions}" /etc/snort.conf

我收到此错误:

sed: -e expression #1, char 24: expected newer version of sed

我收到此错误,因为我的变量中有美元符号。我想用sed,perl,awk或其他任何我可以使用的方法在一个内衬中解决这个问题。

为了澄清,我发布了一个示例输入和预期输出:

输入:

# List of snmp servers on your network
var SNMP_SERVERS $HOME_NET

# Configure your service ports.  This allows snort to look for attacks destined

预期产出:

# List of snmp servers on your network
var SNMP_SERVERS $HOME_NET
var SSH_SERVERS $HOME_NET
var FTP_SERVERS $HOME_NET
var SIP_SERVERS $HOME_NET

# Configure your service ports.  This allows snort to look for attacks destined

2 个答案:

答案 0 :(得分:2)

使用gnu awk你可以这样做:

# no need to escape the $ if you use single quotes
ipvar_definitions='var SSH_SERVERS $HOME_NET
var FTP_SERVERS $HOME_NET
var SIP_SERVERS $HOME_NET'

# use awk command to insert ipvar_definitions after a line containing "var SNMP_SERVERS"
awk -v var="$ipvar_definitions" '1; /var SNMP_SERVERS/{print var}' /etc/snort.conf

<强>输出:

# List of snmp servers on your network
var SNMP_SERVERS $HOME_NET
var SSH_SERVERS $HOME_NET
var FTP_SERVERS $HOME_NET
var SIP_SERVERS $HOME_NET

# Configure your service ports.  This allows snort to look for attacks destined

答案 1 :(得分:0)

$ export ipvar_definitions='
var SSH_SERVERS $HOME_NET
var FTP_SERVERS $HOME_NET
var SIP_SERVERS $HOME_NET
'

$ perl -pe 's/.*var SNMP_SERVERS.*/$&$ENV{ipvar_definitions}/' /etc/snort.conf 
# List of snmp servers on your network
var SNMP_SERVERS $HOME_NET
var SSH_SERVERS $HOME_NET
var FTP_SERVERS $HOME_NET
var SIP_SERVERS $HOME_NET


# Configure your service ports.  This allows snort to look for attacks destined

进一步阅读:https://perldoc.perl.org/Env.html