我正在尝试安装Nagios插件,该文件名为nagios,并且是用PERL编写的 - 这个文件将帮助我们将Nagios docker警报系统与slack集成。
我需要做的是使用sed打开文件,在第120行和第304行找到特定的模式,并在每行的末尾添加变量内容。
#!/usr/bin/env bash
# go into temp dir and do the following
cd /tmp/ && wget https://raw.github.com/tinyspeck/services-examples/master/nagios.pl
mv /tmp/nagios.pl /tmp/slack_nagios.pl && chmod +x /tmp/slack_nagios.pl
# define two variables adding1 and adding2, then add value to each one
read -d '' adding1 <<"BLOCK"
-field HOSTALIAS="$HOSTNAME$"
-field SERVICEDESC="$SERVICEDESC$"
-field SERVICESTATE="$SERVICESTATE$"
-field SERVICEOUTPUT="$SERVICEOUTPUT$"
-field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
BLOCK
read -d '' adding2 <<"BLOCK"
-field HOSTALIAS="$HOSTNAME$"
-field HOSTSTATE="$HOSTSTATE$"
-field HOSTOUTPUT="$HOSTOUTPUT$"
-field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
BLOCK
## Print the two new variables
echo $adding1
echo $adding2
#### Now use seed to change the content of slack_nagios.pl file and save it as new file
echo "Execute sed"
# On file lines 31 to 50 uncomment it
sed -e '31,50 s/#//' \
-e 's/my $opt_token = ""/my $opt_token = "someTokenHere"/' \
-e 's/foo.slack.com/somedomainName.slack.com/' \
# Add toke info and replace slack domain name
-e 's/#alerts/#nagios_alerts/' \
-e 's/#ops/#nagios_alerts/' \
# Find two patterns in the file and replace with nagios_alerts
-e 's|/usr/local/bin|/usrPATH/local/nagiosPATH/etc/dirPATH|g' \
# Replace the deafult path by the new path
###HERE IS WHERE I HAVIN PROBLEMS##
-e '44 s/^nagios_alerts\|\'$'\|${adding1}|g' \
-e '49 s/^nagios_alerts\|\'$'\|${adding2}|g' \
# What I want to do is, on lines 44 and line 49 find the pattern nagios_alert
# And append the value of $adding1 at end of line 44 and append the value of $adding2 on line 49
# But I am getting the following error [ sed: 1: "44 s/^nagios_alerts///| ...": bad flag in substitute command: '/' ]
<slack_nagios.pl >slack_new_nagios.pl
# Count the number of line on the file to confirm that is correct
nbLines=$(cat -n slack_new_nagios.pl | tail -n 1 | cut -f1 | xargs)
echo $nbLines
#echo $file
echo "All Done"
答案 0 :(得分:0)
我没有花足够的时间来理解您的具体示例,但您要解决的一般问题是
sed '120,304{/pattern/s/$/add_this_to_end_of_line/}' file
请注意,这可以转换为awk,如果您需要进行更复杂的更改,这将为您提供更多功能
awk 'NR>=120 && NR<=304 && /pattern/{$0=$0 "add this"}1' file