简体   繁体   English

如何使用Shell将Nginx虚拟主机(config)文件拆分为小文件

[英]How to split a nginx virtual host (config) file into small ones using shell

I have a nginx server and it has around 30+ virtual host block in a single file. 我有一个nginx服务器,它在一个文件中有大约30多个虚拟主机块。 All the virtual host block go like that: 所有虚拟主机块都是这样的:

    server
       {
    #concrete configuration items
    server_name    myserver.hostname.com;
    #concrete configuration items
    #and so on....

    }

My question is how can I split every server block into a single file named by server_name value? 我的问题是如何将每个服务器块分割成一个由server_name值命名的文件? for example the above server block save to a file named myserver.hostname.com.conf I would like to use shell code to complete this task. 例如,上面的服务器块保存到名为myserver.hostname.com.conf的文件中,我想使用shell代码来完成此任务。

By the way, I not sure whether it is a good idea to make every virtual host has its config file.But I did thing as virtual host increasing it became a messy to stuck them all in a common file. 顺便说一句,我不确定让每个虚拟主机都有其配置文件是否是一个好主意,但随着虚拟主机的增加,将它们全部粘贴到一个公共文件中变得很麻烦。

You can use csplit command to split file by context: 您可以使用csplit命令按上下文拆分文件:

$ csplit input.conf '/^\s*server\s*$/' {*}

Then mv (rename) those files to server_name from content: 然后将这些文件从目录中mv (重命名)为server_name

$ for i in xx*; do mv $i `grep -oPm1 '(?<=server_name).+(?=;)' $i`; done

This script will split the input file into smaller ones: 此脚本会将输入文件拆分为较小的文件:

#!/bin/bash
if [ "$1" == "" ]; then
  echo "USAGE: $0 [filename]"
  exit;
fi
# rm xx* *.conf'; # uncomment to re-un
csplit "$1" '/^\s*server\s*{*$/' {*}
for i in xx*; do
  new=$(grep -oPm1 '(?<=server_name).+(?=;)' $i|sed -e 's/\(\w\) /\1_/g'|xargs);
  if [[ -e $new.conf ]] ; then
    cat "$i">>$new.conf
    rm "$i"
  else
    mv "$i" $new.conf
  fi
done

Based on Kev's answer, I wrote the modified script below. 基于Kev的回答,我在下面编写了修改后的脚本。

    #!/bin/bash
    rm xx*
    csplit port80 '/\s*\<server\>\s*/' {*}
    #new_name =''
    for i in xx*
    do
        if grep -oP '(?<=server_name).+;' $i
        then
            result=`grep -oP '(?<=server_name).+;' $i`
            new_name=`echo $result|awk '{print $1}'`
            new_name=${new_name%';'}
            mv $i $new_name
        else
            rm $i
        fi
    done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM