【问题标题】:How to split a nginx virtual host (config) file into small ones using shell如何使用 shell 将 nginx 虚拟主机(配置)文件拆分为小文件
【发布时间】:2012-03-26 22:57:48
【问题描述】:

我有一个 nginx 服务器,它在一个文件中有大约 30 多个虚拟主机块。 所有的虚拟主机块都是这样的:

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

    }

我的问题是如何将每个服务器块拆分为一个由 server_name 值命名的文件?例如上面的服务器块保存到名为 myserver.hostname.com.conf 的文件中 我想用shell代码来完成这个任务。

顺便说一句,我不确定让每个虚拟主机都有自己的配置文件是否是个好主意。但是我做的事情是随着虚拟主机的增加,将它们全部放在一个公共文件中变得很麻烦。

【问题讨论】:

    标签: shell configuration-files


    【解决方案1】:

    您可以使用csplit 命令按上下文拆分文件:

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

    然后将mv(重命名)这些文件从内容改为server_name

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

    【讨论】:

    • 感谢推荐。我试试你的脚本,没有按预期工作,这很奇怪..
    • 可能是注释掉的块也有“服务器”的原因?
    • 我发现问题了! csplit input.conf '/\s*\\s*/' {*} 现在它可以排除像“server_name”这样的实体:D
    • for 脚本很好,虽然我不完全理解它们。当然,它们仍然需要一些调整才能更健壮。
    • 很高兴看到使用 csplit 等经典工具的解决方案。 :)
    【解决方案2】:

    根据 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
    

    【讨论】:

    【解决方案3】:

    此脚本会将输入文件拆分为更小的文件:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2013-08-05
      • 2018-05-20
      • 2014-01-31
      相关资源
      最近更新 更多