【问题标题】:Regex: Check that file contains a line three times正则表达式:检查文件是否包含一行三次
【发布时间】:2022-01-06 08:34:08
【问题描述】:

如何使用正则表达式检查文件是否包含相同的行“这是 123”(带有缩进)精确 3 次?

文件:

<dev>
  <source file='/path/to/file'/>
  <string>this is 123</string>
</dev>

<dev>
  <source dev='this dev'/>
  <string>this is 123</string>
</dev>

<dev>
  <source dev='another dev'/>
  <string>this is 123</string>
</dev>

【问题讨论】:

    标签: regex bash


    【解决方案1】:

    你可以使用 awk 来计算行数

    awk '/  <string>this is 123</string>/ { count++ } END { print count }' file.txt
    

    要使用的字符串包含在/s 中。 在 awk 遇到的每一行之后,它都会增加一个 count,当它到达 END 时,它会打印计数

    使用该计数在条件中进行比较

    c=$(awk '/  <string>this is 123</string>/ { count++ } END { print count }' file.txt)
    if [[ c -eq 3 ]]; then
        # do stuff
    fi
    

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 2021-06-22
      • 1970-01-01
      • 2021-12-30
      • 2021-01-06
      相关资源
      最近更新 更多