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

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匹配关键字后偶数行插入字串的技巧)