sed命令语法中的调用变量

时间:2019-01-31 00:19:20

标签: bash variables sed

我正在创建一个脚本,以更轻松地允许我的组织将工作站添加到我们的Nagios监视系统中。

每次脚本运行时,我都希望能够输入主机名,别名和地址(作为用户输入的变量),并在sed命令中使用名为WITHIN的变量,以便“创建”新的主机要快得多,然后全都输入。

我正在尝试在sed找到之后添加整个字符串 “主机地址}”

我认为是/ a的

(在找到所述字符串后追加) 尽管如此,使用双引号仍不允许调用变量。

#!bin/bash

# Prompt for hostname, alias, and IP address of new host
# take user input has variable to be used in sed 

# Takes user input for hostname
echo host_name : 
read var_hostname    
# Takes user input for alias
echo alias : 
read var_alias
# Takes user input for ip address
echo address : 
read var_address
# searches for the top-most instance "address of the host" within the     windows.cfg file
# after said instance is found, appends the new string below, which calls     for the variables received 
# previously by user
sed -i -e  " address of the host } /a 
define host{
    use             windows-server  ; Inherit default values from a     template
    host_name       $var_hostname       ; The name we are giving to this     host
    alias           $var_alias       ; A longer name associated with the host
    address         $var_address     ; IP address of the host
    }" 
    windows.cfg        

我希望使用用户输入的变量将字符串“ define host {}”写入文件。

1 个答案:

答案 0 :(得分:1)

用于修改 windows.cfg

的文件
 cat windows.cfg 
#some settings
#more settings
test
abc

lot of stuff

test2

backup

 address of the host }

Sed脚本:

 cat sed.sh 
#!/bin/bash

# Prompt for hostname, alias, and IP address of new host
# take user input has variable to be used in sed

# Takes user input for hostname
echo host_name :
read var_hostname
# Takes user input for alias
echo alias :
read var_alias
# Takes user input for ip address
echo address :
read var_address
# searches for the top-most instance "address of the host" within the     windows.cfg file
# after said instance is found, appends the new string below, which calls     for the variables received
# previously by user
sed -e  '/address of the host }/r'<(
echo "define host{"
echo "   use             windows-server  ; Inherit default values from a template"
echo "   host_name       $var_hostname       ; The name we are giving to this host"
echo "   alias           $var_alias       ; A longer name associated with the host"
echo "   address         $var_address     ; IP address of the host"
echo "   }") -i -- windows.cfg

执行:

 ./sed.sh 
host_name :
allan.com
alias :
allan
address :
123.123.123.123

输出:

 cat windows.cfg 
#some settings
#more settings
test
abc

lot of stuff

test2

backup

 address of the host }
define host{
   use             windows-server  ; Inherit default values from a template
   host_name       allan.com       ; The name we are giving to this host
   alias           allan       ; A longer name associated with the host
   address         123.123.123.123     ; IP address of the host
   }

说明:

我决定不使用a,而是在r中使用sed命令(读取文件内容以插入文件)。然后,我使用符号<() 使echo操纵的所有sed命令的输出就好像是一个文件一样。这样可以避免将sed{ char混淆,并提供更好的可读性。

进程替换:http://tldp.org/LDP/abs/html/process-sub.html