【问题标题】:syntax checking for config files配置文件的语法检查
【发布时间】:2016-08-17 03:52:35
【问题描述】:

我需要检查一些配置文件的语法。

配置格式如下:

[sect1]
sect1file1
sect1file2
[sect1_ends]

[sect2]
sect2file1
sect2file2
[sect2_ends]

我的要求是检查sect1 的开头,它在方括号[sect1] 内,然后检查文件sect1file1sect1file2 是否存在,然后通过阅读@ 检查sect1 的结尾987654327@ 内方括号[sect1_ends]。然后对sect2 重复相同的操作,以此类推。

已经有一组允许的部分名称。我的目标是检查部分名称是否在列表中,以及语法是否没有任何错误。

我尝试过使用

 perl -lne 'print $1 while (/^\[(.*?)\]$/g)' <config filename>

但我不确定如何检查和浏览文件。

【问题讨论】:

  • 首先弄清楚你的支票是什么。然后决定工具。将grep 用于这些部分并与部分列表进行比较是否可以,或者您是否应该使用awkperl 制作一个小程序。
  • 感谢@walter,但 grep 无济于事,因为我必须在 start 检查 sect1 是否包含在正方形中括号并出现在允许的部分名称列表中,在验证之后,我需要检查为该 sect1 定义的 files 是否存在,最后检查 sect1 已在方括号内使用 sect1_ends 正确终止。然后跟踪 sect1 语法是否 有效 并继续 sect2 即使它是 invalid 最后我需要打印所有无效的语法部分以便用户更正。
  • 尝试使用 while read -r linel do ... done &lt; inputfile 之类的东西,在你的循环中使用 inSection="sect1"if [ -f "${inSection}file1" ] 之类的东西
  • 非常感谢@walter 我已经开始逐行阅读while 并根据内容决定应该做什么,但仍然跟踪无效sect 并继续通过其他零件有点复杂。

标签: linux bash perl scripting


【解决方案1】:

很高兴看到您尝试过。用这个原型再试一次:

while read -r line; do
   if [ ${#line} -eq 0 ]; then
      continue # ignore empty lines
   fi
   if [[ "${line}" = \[*\] ]]; then
      echo "Line with [...]"
      if [ -n "${inSection}" ]; then
         if [ "${line}" = "${inSection/]/_ends]}" ]; then
            echo "End of section"
            unset inSection
         else
            echo "Invalid endtag ${line} while processing ${inSection}"
            exit 1
         fi
      else
         echo "Start of new section ${line}"
         inSection="${line}"
      fi
   else
      if [ -f "${line}" ]; then
         echo "OK file ${line}"
      else
         echo "NOK file ${line}"
      fi
   fi
done < inputfile

【讨论】:

  • 哇,逻辑就像一个魅力,我即兴创作它以包含更多我的要求。非常感谢。
  • 我很高兴这成功了。你可以接受答案,然后把钱存入你的银行账户。
【解决方案2】:

您的解决方案看起来不错,但是 -n reads lines from standard input (STDIN)。您需要将配置文件输入 STDIN 以将其传递给您的脚本:

perl -lne 'print $1 while (/^\[(.*?)\]$/g)' <config.ini

替代选项将使用-p

【讨论】:

  • 感谢@sebastian 解决了以方括号开头和结尾的捕获行,这将有助于捕获[sect][sect_ends],但我不确定逻辑应该如何通过。正如@walter i 所建议的那样已经开始使用while 循环逐行读取,确定它是否是有效的sect start,然后遍历所有后续行直到sect_ends 并验证sect_ends 是否对应于sect start
猜你喜欢
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
相关资源
最近更新 更多