Bash,排除for循环和引号中的文件

Bash,排除for循环和引号中的文件,bash,for-loop,quotes,Bash,For Loop,Quotes,我希望在for循环中处理目录中的文件,同时排除一些以前处理过的文件。我在用!要排除文件,但当要排除的文件在文件名中有空格且我从文件中读取文件名时,如何引用变量 我可以用!当我明确声明要排除的文件时,没有问题: $ mkdir test $ cd test $ touch this.txt and\ this.txt not\ this.txt nor\ this.txt $ for THEFILE in !(not this.txt|nor this.txt); do echo $T

我希望在for循环中处理目录中的文件,同时排除一些以前处理过的文件。我在用!要排除文件,但当要排除的文件在文件名中有空格且我从文件中读取文件名时,如何引用变量

我可以用!当我明确声明要排除的文件时,没有问题:

$ mkdir test
$ cd test
$ touch this.txt and\ this.txt not\ this.txt nor\ this.txt

$ for THEFILE in !(not this.txt|nor this.txt); do 
    echo $THEFILE
  done

and this.txt
this.txt
但是当我引入exclude文件时,如果文件名中有带空格的文件,我很难正确引用变量。以下是不带引号的输出:

$ cd ..
$ SRCDIR=test
$ EXCLUDEFILE=excludes.txt
$ cat > excludes.txt
not this.txt|nor this.txt
^D

$ for THEFILE in $SRCDIR/!($(cat $EXCLUDEFILE)); do
  echo $THEFILE
done

test/!(not
this.txt|nor
this.txt)
下面是一个带引号的例子:

$ for THEFILE in $SRCDIR/!("$(cat $EXCLUDEFILE)"); do
  echo $THEFILE
done

test/and this.txt
test/nor this.txt
test/not this.txt
test/this too.txt
test/this.txt

我尝试过其他一些变体,但没有成功。所以,请教育我。

一个简单且可移植的解决方法是

filter=$(cat excludes.txt)
for THEFILE in $SRCDIR/*; do
    case "|$filter|" in *"|$THEFILE$|"*) continue;; esac
    echo "$THEFILE"
done
我可能会在excludes.txt中使用换行符作为分隔符,尽管这会使代码有点不确定。要实现完全健壮的处理,请使用文本零字节,或者如果您不需要处理目录,请使用斜杠。

好的,我放弃了cat,选择了while:

现在它似乎起作用了

我讨厌猫

$ for THEFILE in $SRCDIR/!($(while read i; do echo -n $i\|;done<$EXCLUDEFILE)); do 
  echo $THEFILE
done

test/and this.txt
test/foo.txt
test/this too.txt
test/this.txt