Issue
I need dynamic change nginx config for ci, try work it out by sh script.
But i'm zero in sh scripts, i know only what i see in google.
Input:
server {
#location /api/graphql {
# modsecurity off;
# proxy_pass http://10.1.0.4;
#}
location 73347347 {
proxy_pass 123;
}
location 123 {
proxy_pass 123;
}
location / {
modsecurity off;
proxy_pass http://10.1.0.4;
}
}
test.sh
location="
location /projects/$1/$2 {
proxy_pass http://10.1.0.6:$3; #where $arg, on output i just show $1 for example
}"
#sed "/.*#location/! s/.*location/$location\n\n&/" file
#sed "/.*#location/!s/.*location/$location\n\n&/" file
#sed "/#location/n;/location/i 0000" file
awk "!done && match($0,/^([[:space:]]*)location/,a){print a[1] $location ORS; done=1} 1" file
./test.sh test 2.0.0 5000
Output:
server {
#location /api/graphql {
# modsecurity off;
# proxy_pass http://10.1.0.4;
#}
location /projects/test/2.0.0 {
proxy_pass http://10.1.0.6:5000;
}
location 73347347 {
proxy_pass 123;
}
location 123 {
proxy_pass 123;
}
location / {
modsecurity off;
proxy_pass http://10.1.0.4;
}
}
I have worrking command, but she paste before all matches:
sed "/.*#location/! s/.*location/$location\n\n&/" file
Solution
Using any awk:
$ cat tst.sh
#!/usr/bin/env bash
location='\
location /projects/'"$1/$2"' {
proxy_pass http://10.1.0.6:$3; #where $arg, on output i just show $1 for example
}
'
awk -v loc="$location" '
!done && ($1 == "location") {
print loc
done = 1
}
{ print }
' file
$ ./tst.sh test 2.0.0
server {
#location /api/graphql {
# modsecurity off;
# proxy_pass http://10.1.0.4;
#}
location /projects/test/2.0.0 {
proxy_pass http://10.1.0.6:$3; #where $arg, on output i just show $1 for example
}
location 73347347 {
proxy_pass 123;
}
location 123 {
proxy_pass 123;
}
location / {
modsecurity off;
proxy_pass http://10.1.0.4;
}
}
See How do I use shell variables in an awk script? for more information on how to pass the content of a shell variable to an awk script.
The above awk script is simpler than the one in the answer to your previous question because here you're providing the indenting for the new text in the variable definition whereas with the previous one we had to figure out the indent from the existing input.
Answered By - Ed Morton Answer Checked By - Pedro (WPSolving Volunteer)