【问题标题】:Check all files in directory whether they contain specific string two or more times检查目录中的所有文件是否包含特定字符串两次或更多次
【发布时间】:2018-10-18 20:00:55
【问题描述】:

我想检查目录中的所有文件是否可以包含两次或多次出现的字符串。

检查单个“occurrence of a specific string using bash”似乎很容易:

if grep -q "LineString" "$File"; then
  Some Actions # SomeString was found
fi

但是如何数到二呢?

【问题讨论】:

  • 使用-c 开关。这将返回匹配行的计数作为 grep 的输出
  • 你能给我们一个文件样本和要搜索的字符串吗
  • 下面的答案应该可以满足您的要求。

标签: bash grep


【解决方案1】:

使用(( )) 进行数字比较:

if (( $(grep -c -- "LineString" "$file") >= 2 )); then
  # your logic
fi

循环遍历所有文件:

#!/bin/bash
shopt -s nullglob # make glob expand to nothing if there are no matching files
for file in *; do
    [[ -f $file ]] || continue
    if (( $(grep -c -- "LineString" "$file") >= 2 )); then
      # your logic
    fi
done

如果您正在处理非常大的文件并且您的grep 支持-m 选项,那么您可以使用grep -cm 2 来优化读取:

#!/bin/bash
shopt -s nullglob
for file in *; do
    [[ -f $file ]] || continue
    if (( $(grep -cm 2 -- "LineString" "$file") >= 2 )); then
      # your logic
    fi
done

【讨论】:

  • 请注意-cgrep 的标准选项,但-m 不是。 (另外,它可能取决于实现,但-m-c 可以结合使用以避免使用wc -l。)
  • 从第二个答案我得到一个“意外的 fi”错误。我不应该用 done 关闭 for() 循环吗?对于 * 中的文件;做 [[ -f $file ]] ||继续 filename="${file##*/}" echo $filename if (( $(grep -c -- "LineString" "$file") >= 2 ));然后 mv $file "$filename.bak" echo "select ST_LineMerge(ST_Union(geometry)) from $file"; ogr2ogr -f GeoJSON -explodecollections -dialect sqlite -sql \ "select ST_LineMerge(ST_Union(geometry)) from $file" "$filename.geojson" "$filename.bak" fi done
  • 更正了答案。
  • 谢谢@chepner。更新了答案以纳入您的建议。
  • 由于合并“MultiLineStrings”不起作用 - 我可以将它们从搜索中排除吗? (抱歉,有点搞笑!)
【解决方案2】:

试试这个

if [ `grep "LineString" $file | wc -l` -gt 1 ]; then 
    echo "done found";
    ' do something
fi;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多