sed 删除匹配行的指定字符串

这里以nginx配置文件为例,修改日志格式。

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

改成

    log_format  main  '[$time_iso8601] - $remote_addr "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

这需要匹配log_format这行,删除[$time_local]字符串,其余做替换即可。

  • 第一步:
# sed "s/\$remote_addr/[\$time_iso8601]/" 1.txt

    log_format  main  '[$time_iso8601] - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
  • 第二步:
# sed -e "s/\$remote_addr/[\$time_iso8601]/" -e "s/\$remote_user/\$remote_addr/" 1.txt

    log_format  main  '[$time_iso8601] - $remote_addr [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
  • 第三步:
# sed -e "s/\$remote_addr/[\$time_iso8601]/" -e "s/\$remote_user/\$remote_addr/" -e "s/\[\$time_local\] //" 1.txt

    log_format  main  '[$time_iso8601] - $remote_addr "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

另外,如果想在一行行尾增加字符串,通常是这样做:

# sed 's/$/aaa/' file1				# ^表示行首,$表示行尾

但如果将

access_log /usr/local/nginx/logs/$SERVICE_access.log;

改成

access_log /usr/local/nginx/logs/$SERVICE_access.log json;

用上面的方法是不可行的,还是需要替换字符串

# cat 2.txt
    access_log /usr/local/nginx/logs/aaaaa_access.log;
    
# SERVICE=aaaaa; sed "s/\/usr\/local\/nginx\/logs\/"$SERVICE"_access.log;/\/usr\/local\/nginx\/logs\/"$SERVICE"_access.log json;/" 2.txt
    access_log /usr/local/nginx/logs/aaaaa_access.log json;

其实不是$name要加双引号,而只是用于结束前面的双引号,和再开始后面的双引号,从而将$name置入双引号外面的shell环境中,才能得到shell解析。双引号内为sed环境。


你可能感兴趣的:(#,Linux小知识)