How to insert text into a conf file?
In nginx.conf
I have:
server {
listen 81;
...snip...
}
I want the file to look like this:
server {
listen 81;
if (-f $document_root/system/maintenance.html) {
return 503;
}
...snip...
}
So the text (if..
) should only be inserted if it does not already exist.
Is this possible to do using some in-built program at the command line?
Something like:
- Open a file
- See if it has certain text in it
- If it does not then locate certain text (
listen 81;
) and on the next line a开发者_C百科fter it insert a few lines of text
This is a job for sed
, wrapped up in a shell script. Completely untested; invoke as "./script /path/to/nginx.conf"; note that it does not look for the complete text you wanted to add, only a hopefully-sufficiently-long token from its first line.
#! /bin/sh
if grep -q "document_root/system/maintenance" "$1"
then :
else
set -e
sed < "$1" > "$1.tmp" \
'/listen 81;/a\
if (-f $document_root/system/maintenance.html) {\
return 503;\
}
'
mv -f "$1.tmp" "$1"
fi
精彩评论