【问题标题】:Regex to match nginx location block?正则表达式匹配 nginx 位置块?
【发布时间】:2021-09-05 22:10:28
【问题描述】:

我正在开发一个 bash 脚本,该脚本可以将 nginx 位置块添加到采用 URL 的文件中。为防止重复,此脚本也会在已存在的情况下将其删除。

为了删除已经存在的块,我制作了下面的正则表达式。 ^location\s\/${URLGOESHERE} {[\s\S]*?(?=\n{2,})$

正则表达式需要像这样匹配整个多行块:

location /URLGOESHERE {
  try_files $uri /URLGOESHERE/index.php?$query_string;
}

我希望正则表达式匹配块内的任何内容,直到右括号} 文件内将有多个块 例如

location /URL1HERE {
  expires 7d;
  try_files $uri /URLGOESHERE/index.php?$query_string;
  allow all;
  Etc....
}

location /URL2HERE {
  try_files $uri /URLGOESHERE/index.php?$query_string;
}
location /URL3HERE {
  try_files $uri /URLGOESHERE/index.php?$query_string;
}

location /URL4HERE {
  expires 7d;
  try_files $uri /URLGOESHERE/index.php?$query_string;
  allow all;
  Etc....
}

我制作的正则表达式有效,但前提是块前后有空行。因此,对于我的正则表达式 URL2,pcgrep 找不到 3(之前或之后没有换行符)和 4(文件末尾没有换行符)

我想知道是否可以使正则表达式完全匹配块而不需要这些空行。

【问题讨论】:

    标签: regex unix-text-processing


    【解决方案1】:

    编辑: 由于 OP 已更改示例,因此现在添加以下解决方案。仅基于当前显示的示例。

    awk '/location \/URL([0-9]+)?HERE[[:space:]]+?/{found=1} found; /}/ && found{found=""}'  Input_file
    


    使用您显示的示例/尝试,请尝试遵循awk 代码。这将使 { 到 } 之间的语句从中删除新行。

    awk -v RS='location[[:space:]]+/URLGOESHERE[[:space:]]+{\n*[[:space:]]+try_files[[:space:]]+\\$uri[[:space:]]+\\/[^?]*\\?\\$query_string;\n*}' '
    RT{
      gsub(/.*\n*{\n*[[:space:]]+/,"",RT)
      gsub(/\n*}/,"",RT)
     print RT
    }
    '  Input_file
    

    说明:根据显示的示例制作字段分隔符以匹配值以获取包含空行的位置块,然后在每个匹配的分隔符值中删除空行。

    例如,假设我们有以下 Input_file:

    cat Input_file
    location /URLGOESHERE {
    
      try_files $uri /URLGOESHERE/index.php?$query_string;
    
    
    
    }
    
    location /URLGOESHERE {
      try_files $uri /URLGOESHERE/index.php?$query_string;
    }
    

    运行上述代码后,我们将得到以下输出

    try_files $uri /URLGOESHERE/index.php?$query_string;
    try_files $uri /URLGOESHERE/index.php?$query_string;
    

    所用正则表达式的解释:为上述代码添加详细解释。

    location[[:space:]]+/URLGOESHERE   ##Matching location followed by spaces followed by /URLGOESHERE
    [[:space:]]+{\n*                   ##Followed by spaces { and 0 or more new lines.
    [[:space:]]+try_files[[:space:]]+  ##Followed by spaces try_files followed by 1 or more spaces.
    \\$uri[[:space:]]+                 ##followed by $uri spaces here.
    \\/[^?]*\\?\\$query_string;\n*}    ##followed by / till ? occurrence followed by $query_stirng; followed by 0 or more new lines.
    

    【讨论】:

    • 您好 Ravinder 非常感谢这个,我非常感谢您的帮助,但我不确定这是否是我的意思。我正在寻找一个正则表达式,它将匹配位置块的开头到结尾,包括大括号。块中可能有任意数量的行然后我可以将 URL 传递到正则表达式中,如果该块存在,它将检查配置文件,如果它已经存在,则将其删除。
    • @azy141,请编辑您的问题,提供更多输入和预期输出的详细信息,以便我更清楚地理解它,谢谢。
    • 我已经更新了问题以包含更多细节:)
    • @azy141,好的,我现在已经添加了 EDIT 解决方案,请检查一次,让我知道它是怎么回事。
    猜你喜欢
    • 2017-01-03
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2022-06-10
    相关资源
    最近更新 更多