Bash grep避免检查目录

时间:2014-02-25 22:04:28

标签: bash grep

我收到错误,因为我搜索子目录,我不希望它只搜索这个文件夹中的文件。其他文件夹是LOGS和RESULTS,包含其他文件。你如何停止只搜索下载中的文件?

is_file_contains_VAR()
{
grep -q -e "$VAR" "$1"

}

for f in *
do
   if [ -f "$f" ]; then
      if is_file_contains_VAR"$f"; then
    echo "FILE exist in " $f

    #echo "Processing $f file..."

        # take action on each file. $f store current file name
    #cat $f
    else
        echo "echo "FILE DOES NOT exist in " $f
     fi

 done

3 个答案:

答案 0 :(得分:4)

添加

[ -d "$f" ] && continue

在循环开始时。如果$f是一个目录,它将被跳过。

顺便说一句,您可能会考虑应该导致哪些设备文件,fifos和符号链接。也许您想使用[ -f "$f" ] || continue来检查常规文件(以及指向常规文件的符号链接)。

答案 1 :(得分:2)

您可以使用find代替通用*来迭代特定文件:

find . -maxdepth 1 -type f -print0 |
while read -d '' -r file; do
    do_something_with "$file"
done

-maxdepth 1阻止查找从子目录下降。

我假设GNU找到。

总是引用您的"$variables",除非您特别知道何时不引用它们。

答案 2 :(得分:1)

你可以这样做:

cd Downloads/
for f in *
do
   [[ -f "$f" ]] && is_file_contains_VAR "$f" && echo "found"
done

修改

for f in *
do
   if [ -f "$f" ]; then
      if is_file_contains_VAR "$f"; then
          echo "FILE exist in $f"
      else
          echo "echo "PATTERN DOES NOT exist in $f"
      fi
   fi
done