美文网首页
【shell】sed匹配关键字后偶数行插入字串的技巧

【shell】sed匹配关键字后偶数行插入字串的技巧

作者: 景贤游子_小跟班 | 来源:发表于2020-05-27 06:49 被阅读0次

    nginx配置X-Forwarded-For时sed和awk的使用技巧

    知识点:

    1、匹配偶数行:awk -F':' '!(NR%2){print $1}'
    
    2、匹配行后插入:sed -i "${NUM}a\            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;" ${conf_path}
    
    完整脚本如下:
    #!/bin/bash
    export PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
    conf_path="/usr/local/nginx/conf/nginx.conf"
    XFF=$(grep 'X-Forwarded-For' ${conf_path})
    if [ "${XFF}" ];then
        echo "X-Forwarded-For已配置"
        exit 0
    fi
    cp ${conf_path} /tmp/nginx.conf.bak
    LINE_NUM=$(grep -n 'proxy_set_header  X-Real-IP' ${conf_path}|awk -F':' '!(NR%2){print $1}')   
    #LINE_NUM 总共4行
    flg=0
    for NUM in ${LINE_NUM}
        do
        if [ "${flg}" -eq 1 ];then
            NEW_NUM=$((${NUM}+1))   
            sed -i "${NEW_NUM}a\            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;" ${conf_path}
        else
            sed -i "${NUM}a\            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;" ${conf_path}
        fi
        ((flg++))
    done
    cd /usr/local/nginx/op/;./reload.sh && exit 0 || exit 1
    

    相关文章

      网友评论

          本文标题:【shell】sed匹配关键字后偶数行插入字串的技巧

          本文链接:https://www.haomeiwen.com/subject/uxjiahtx.html