如何通过命令 sed/awk/another 在文件中第一个匹配之前粘贴另一个位置?

问题描述 投票:0回答:1

我需要动态更改 ci 的 nginx 配置,尝试通过 sh 脚本解决。

但我对 sh 脚本为零,我只知道我在 google 中看到的内容。

输入:

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;
    }

}

测试.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测试2.0.0 5000

输出:

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;
    }

}

我有工作命令,但她在所有匹配之前粘贴:

sed "/.*#location/! s/.*location/$location\n\n&/" file

awk sed
1个回答
0
投票

使用任何 POSIX 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 && /^([[:space:]]*)location/ {
        print loc
        done = 1
    }
    { print }
' file

$ ./tst.sh foo bar
server {

    #location /api/graphql {
    #       modsecurity off;
    #       proxy_pass http://10.1.0.4;
    #}

    location /projects/foo/bar {
        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;
    }

}

请参阅如何在 awk 脚本中使用 shell 变量?,了解有关如何将 shell 变量的内容传递到 awk 脚本的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.