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

孤街醉人 提交于 2019-12-14 02:24:26

问题


I have a nginx server and it has around 30+ virtual host block in a single file. 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? 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.

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.


回答1:


You can use csplit command to split file by context:

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

Then mv(rename) those files to server_name from content:

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



回答2:


Based on Kev's answer, I wrote the modified script below.

    #!/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



回答3:


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


来源:https://stackoverflow.com/questions/9634953/how-to-split-a-nginx-virtual-host-config-file-into-small-ones-using-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!