发现发出意外的“。”,使 wc -l 列出比预期更多的内容

find emitting unexpected ".", making wc -l list more contents than expected

我正在尝试使用更新的命令如下:

touch $HOME/mark.start -d "$d1"
touch $HOME/mark.end -d "$d2"
SF=$HOME/mark.start
EF=$HOME/mark.end
find . -newer $SF ! -newer $EF

但这给了我这样的输出:

.
./File5

并将其计为 2 个文件,但是该目录只有 1 个文件,即 File5。为什么会出现这种情况,如何解决?

更新:

我实际上正在尝试 运行 以下脚本:

#!/bin/bash
check_dir () {
  d1=
  d2=$((d1+1))
  f1=`mktemp`
  f2=`mktemp`
  touch -d $d1 $f1
  touch -d $d2 $f2
  n=$(find  \( -name "*$d1*" \) -o \( -newer $f1 ! -newer $f2 \) | wc -l)
  if [ $n !=  ]; then echo  "=" $n ; fi
  rm -f $f1 $f2
}

检查目录中是否有文件具有 YYYMMDD 格式的特定日期,或者其最后修改时间是否为最后 1 天。

check_dir ./dir1 20151215 4
check_dir ./dir2 20151215 3

在 dir1 中应该有 4 个这样的文件,如果不是,那么它将打印那里的实际文件数。

因此,当目录中只有名称中包含日期的文件时,它会检查它们是否正常,但是当它检查较新的文件时,它总是会额外提供 1 个文件(目录中甚至不存在)。为什么会这样???

问题是为什么 find 的结果中有一个额外的 .,即使不存在同名的文件或目录。答案很简单:. 总是存在,即使它是隐藏的。使用ls -a显示隐藏内容,你会看到它存在。


您现有的 find 命令并不能免除目标目录本身 -- . -- 成为合法结果的可能性,这就是为什么您得到的结果比您预期的要多。

添加以下过滤器:

-mindepth 1  # only include content **under** the file or directory specified

...或者,如果您只想计算 文件,请使用...

-type f      # only include regular files

假设 GNU find,顺便说一句,这一切都可以变得更加高效:

check_dir() {
  local d1 d2 # otherwise these variables leak into global scope
  d1=
  d2=$(gdate -d "+ 1 day $d1" '+%Y%m%d') # assuming GNU date is installed as gdate
  n=$(find "" -mindepth 1 \
                -name "*${d1}*" -o \
                '(' -newermt "$d1" '!' -newermt "$d2" ')' \
                -printf '\n' | wc -l)
  if (( n !=  )); then
    echo " = $n"
  fi
}