Cómo dividir un archivo (config) de host virtual nginx en archivos pequeños usando shell

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.

preguntado el 09 de marzo de 12 a las 13:03

3 Respuestas

Puede usar el csplit command to split file by context:

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

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

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

respondido 09 mar '12, 14:03

thanks for recommending. I try you script,didn't work as expect, it's quite weird.. - allan ruina

may be it's cause by the commented out block who has "server" too? - allan ruina

I find the problem! csplit input.conf '/\s*\<server\>\s*/' {*} and now it can exlude entity like "server_name" :D - allan ruina

the for script is good, though I don't understand them all.Of cause they still need some adjustment to be more robut. - allan ruina

Nice to see solutions that use classic tools like csplit. :) - ghoti

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

respondido 11 mar '12, 06:03

could you adapt this to match apache config files too? That would be a solution to that issue then: github.com/rubo77/vhost-split.py/issues/1 - rubo77

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

Respondido 28 Jul 16, 13:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.