sed删除字符串开头的字符

时间:2018-07-03 06:04:23

标签: regex bash nginx sed

我有以下脚本,可在nginx配置中的IP地址之前插入“#”作为注释。

#!/bin/bash
hosts=( 84.19.155.71 84.19.155.72 )
for i in "${hosts[@]}"
do
        CHECK=`grep $i nginx.conf`
        if [[ ! "$CHECK" =~ ^#.*$ ]]
        then
                nc -zw 5 $i 5044
                if [ "$?" != "0" ]
                then
                        sed -i "/$i/s/^/#/" nginx.conf
                else
                        sed -i 's/#*$i/$i/' nginx.conf
                fi
        fi
done

它可以在字符串的开头插入“#”,但是如果nc命令的退出代码为0,我现在想删除它。如上所述,我使用else语句尝试了该操作,但是无济于事。 nginx.conf如下所示:

user root;
worker_processes auto;
pid /run/nginx.pid;
load_module /usr/lib/nginx/modules/ngx_stream_module.so;


worker_rlimit_nofile 1000000;

events {
        worker_connections 20000;
        # multi_accept on;
}

stream {
log_format    basic    '$time_iso8601 $remote_addr '
                       '$protocol $status $bytes_sent $bytes_received '
                       '$session_time $upstream_addr '
                       '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

# Enable access_log statements for debugging
access_log /var/log/nginx/stream.log basic;

  upstream syslog_udp {
    #hash $remote_addr;
    server 84.19.155.71:514 max_fails=2 fail_timeout=5s;
#    server 84.19.155.72:514 max_fails=2 fail_timeout=5s;
  }
  server {
    listen 514 udp;
    proxy_pass syslog_udp;
    proxy_responses 0;
    #proxy_timeout 2s;
    proxy_bind $remote_addr transparent;
    #proxy_next_upstream_timeout 2s;
  }
}

任何人都可以帮助删除IP地址中的“#”字符吗?

2 个答案:

答案 0 :(得分:1)

首先,第一个if语句if [[ ! "$CHECK" =~ ^#.*$ ]]会处理仅不以#开头的行

添加#看起来不错,如果要删除,可以尝试:

sed -i "s/^#*$i//" nginx.conf

答案 1 :(得分:1)

  

如果[[! “ $ CHECK” =〜^#。* $]],这将仅采用不以“#”开头的行   您可能需要重新访问我将不讨论的那部分。

但这是sed替代品,可能对您有帮助。

user@machine:$cat sample 
server 84.19.155.71:514 max_fails=2 fail_timeout=5s;
#server 84.19.155.72:514 max_fails=2 fail_timeout=5s;

user@machine:$sed  "s/^#\(.*$i.*\)/\1/g" sample
server 84.19.155.71:514 max_fails=2 fail_timeout=5s;
server 84.19.155.72:514 max_fails=2 fail_timeout=5s;
相关问题