Bash
1 前言
一个问题,一篇文章,一出故事。
笔者最近需要快速地修改一堆nginx的配置文件,详细的需求是把一个配置文件快速地拆分为两个配置文件。
于是想到使用匹配关键字、然后替换的方法。
总的来说,以后不用挨个修改配置文件,感觉总结此文比较有价值。O(∩_∩)O哈哈~
2 最佳实践
2.1 提前备份配置文件
tar -cvf /data/backup/nginx_conf.tar.bz2 /etc/nginx/
2.2 测试替换命令的作用范围
sourceSring="include /etc/nginx/public/header_safety.conf;" cd /etc/nginx/ for i in `grep -R "$sourceSring" | cut -d":" -f1`; do echo $i done
注:关键字为变量“sourceSring”定义的字符串
2.3 执行替换操作
sourceSring="include /etc/nginx/public/header_safety.conf;" targetString="include /etc/nginx/public/header_HSTS.conf;\n include /etc/nginx/public/header_X-Frame-Options.conf;" cd /etc/nginx/ for i in `grep -R "$sourceSring" | cut -d":" -f1`; do sed -i "s~$sourceSring~$targetString~g" $i done
需要注意的是,
– 以上把变量“sourceSring”定义的字符串替换为变量“targetString”的字符串
– 变量“targetString”字符串使用“\n”换行
2.4 确认执行
cd /etc/nginx/ grep -R "include /etc/nginx/public/header_HSTS.conf;" grep -R "include /etc/nginx/public/header_X-Frame-Options.conf;"
2.5 禁用配置
sourceSring="include /etc/nginx/public/header_HSTS.conf;" targetString="#include /etc/nginx/public/header_HSTS.conf;" cd /etc/nginx/ for i in `grep -R "$sourceSring" | cut -d":" -f1`; do sed -i "s~$sourceSring~$targetString~g" $i done sourceSring="include /etc/nginx/public/header_X-Frame-Options.conf;" targetString="#include /etc/nginx/public/header_X-Frame-Options.conf;" cd /etc/nginx/ for i in `grep -R "$sourceSring" | cut -d":" -f1`; do sed -i "s~$sourceSring~$targetString~g" $i done
没有评论