0

following older posts (How do I use vim on the command line to add text to the middle of a file? & How to insert the content of a file into another file before a pattern (marker)?), I have a more complex case which I need your advice. I have the following Test.conf file:

server {
    listen       80;
    server_name  jenkins2;

    location /DE06/ {
        proxy_pass     http://jenkins2:18015/DE06/;
    }
}

I want to run one command, so in the end, the file content will be:

server {
    listen       80;
    server_name  jenkins2;

    location /DE15/ {
        proxy_pass     http://jenkins2:18015/DE15/;
    }

    location /DE06/ {
        proxy_pass     http://jenkins2:52716/DE06/;
    }
}

means I need to find the first occurrence of the word jenkins2, and then add this content:

location /DE15/ {
    proxy_pass     http://jenkins2:18015/DE15/;
}

any idea what is the right command?

arielma
  • 223
Ariel
  • 101

3 Answers3

0

vim +/jenkins2 +j +":r insert.txt" +gg=G +wq testfile.txt

where insert.txt contains the snippet you want to add and testfile.txt is the file you want do edit.

I'm not sure vim is the best tool to do that, though.

  • +/jenkins2 search for jenkins2
  • +j move down one line
  • ":r insert.txt" read the file to insert. Mind the quotes!
  • +gg=G autoindent the file
  • +wq and write it
markgraf
  • 2,860
0

I've found a working sed command:

sed -i -e '/jenkins5/{ r example.txt' -e '; :L; n; bL;}' nginx_jenkins.conf

When env param is needed, you can use:

sed -i -e '/'${Alias}'/{ r example.txt' -e '; :L; n; bL;}' nginx_jenkins.conf
Ariel
  • 101
0

For fun and learning, as a vimgolf on your example, there is this

vim +"4t4|/D/,/}/t4|'[,s/06/15/|s/52716/18015/|x" file.conf

Commands are separated by | :

  • 4t4 copy line 4 on line 4
  • /D/,/}/t4 from line containing the first D to line containing the next }, copy on line 4
  • '[,s/06/15/ from the first line of the last change to current line (last line of the last change), substitute 06 by 15
  • s/52716/18015/ substitute on current line (where 06 was last substituted)
  • x save changes and exit

:h :copy, :h '[, :h :/

perelo
  • 101