【问题标题】:How to find multiline text in file using bash如何使用 bash 在文件中查找多行文本
【发布时间】:2022-11-27 15:34:18
【问题描述】:

我有一个具有这种结构的文件:

section "first_section" {
  parameter1 = value1
  parameter2 = value2
  parameter3 = value3
}

section "second_section" {
  parameter1 = value1
  parameter2 = value2
  parameter3 = value3
}
...

我有一个包含新部分的变量,例如:


section "third_section" {
  parameter1 = value1
  parameter2 = value2
  parameter3 = value3
}

如果该部分已存在于文件中,我想在添加新部分之前检查 Bash。

我正在尝试类似的东西

if grep -q -z "$section" file.txt
then
  echo "Duplicate found"
else
  echo "$section" >> ./file.txt
fi

但是,我总是得到 Duplicate found 输出,即使它不是真的。

【问题讨论】:

  • 请使用您尝试过的代码和您的代码生成的(错误)结果更新问题;变量是如何填充的(来自文件?在你的脚本中硬编码?用户在命令提示符下输入?)(用这个额外的细节更新问题)
  • 这通常看起来像您想要一个基于 regex 的快速但肮脏的解决方案,这可以在 Bash 中实现,或者一个更结构化的基于解析的解决方案,这可能更适合其他语言。您要找的是哪一个?
  • @BlackBeans 基于正则表达式的快速而肮脏的解决方案可以完成此任务。谢谢!

标签: bash


【解决方案1】:

我会使用 bash 内置模式匹配the [[...]] construct

当使用‘==’和‘!=’运算符时,运算符右边的字符串被认为是一个模式,并根据Pattern Matching中描述的规则进行匹配

contents=$(< filename)
section='section "third" {...}'

if [[ $contents == *"$section"* ]]; then
  echo "file already contains the section"
else
  # append it to the file
  echo "$section" >> filename
end

【讨论】:

    【解决方案2】:

    基于这篇文章 https://unix.stackexchange.com/questions/528146/how-to-grep-multi-lines ,如果你的 GNU grep 支持 P 标志,你可以这样做:

    
    section='section "third_section" {
      parameter1 = value1
      parameter2 = value2
      parameter3 = value3
    }'
    
    if grep -qozP  'section "third_section" {($
    .*){1,}}' file.txt; then
      printf 'Duplicate
    ' >&2
    else
      printf '
    %s' "$section" >> file.txt
    fi
    

    • 假设第三节没有具有不同条目/内容/值的重复条目。

    • 删除-q标志以查看grep的输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 2021-12-06
      • 2011-12-18
      • 2014-03-05
      • 2013-11-30
      • 2011-08-05
      相关资源
      最近更新 更多