0

I am trying to edit an aws elasticbeanstalk nginx config file using sed. I would like to insert a new location block after the default one.

To do this I'm matching a line in the previous location block and then I would like to skip down 8 lines and then insert the text.

This is what it looks like before I run sed

upstream nodejs {
    server 127.0.0.1:8081;
    keepalive 256;
}

server {
    listen 8080;

    location / {
        proxy_pass  http://nodejs;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

and here is my naive attempt at constructing the command which doesn't actually work but instead just sticks the new block under the line containing proxy_pass http://nodejs;.

sed -i '/nodejs;/a \ location ^~ /blog {}' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf

How can I skip 8 lines after the line I identify in my regex. Also suggestions on another way to identify where I want to place my new block are appreciated as well.

2
  • 1
    Could you post what the new config should look like? Jan 5, 2015 at 1:36
  • can you rely on the indention of the } below the location. or of the final }? I think something more advanced like awk may be a better fit to this task.
    – Jasen
    Jan 5, 2015 at 2:32

1 Answer 1

3

This looks for nodejs; and jumps eight lines down and then inserts location ^~ /blog {}. You haven't shown your desired output but, based on the question, I infer that this is what you are looking for:

$ sed '/nodejs;/ {n;n;n;n;n;n;n;n;s/^/    location ^~ \/blog {}\n/}' file
upstream nodejs {
    server 127.0.0.1:8081;
    keepalive 256;
}

server {
    listen 8080;

    location / {
        proxy_pass  http://nodejs;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location ^~ /blog {}
}

How it works

The sed command is:

/nodejs;/ {n;n;n;n;n;n;n;n;s/^/ location ^~ \/blog {}\n/}

This starts by looking for lines containing nodejs; and, when found, executes the statements in braces which follow.

n prints the current pattern space and reads in the next line. We do this eight times. This has the effect of jumping down eight lines.

s/^/ location ^~ \/blog {}\n/ makes the changes on the eighth line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.