尝试弄清楚如何包含除名为manifest.txt
的一个之外的所有.txt
文件。
FILES=(path/to/*.txt)
declare -a files=()
for file in /path/to/files/*
do
! [[ -e "$file" ]] || [[ "$file" = */manifest.txt ]] || files+=("$file")
done
for
语句中使用globbing不会导致文件名中的空格(甚至是换行符)出现问题。
编辑
我添加了一个测试,用于处理globbing失败且未设置nullglob
选项的情况下文件存在的情况。$ touch f{1..6}.txt manifest.txt
$ ls *.txt
f1.txt f3.txt f5.txt manifest.txt
f2.txt f4.txt f6.txt
declare -A exclude
for f in f1.txt f5.txt manifest.txt; do
exclude[$f]=1
done
然后将不在关联数组中的文件添加到一个数组中:
files=()
for fn in *.txt; do
[[ ${exclude[$fn]} ]] && continue
files+=("$fn")
done
$ echo "${files[@]}"
f2.txt f3.txt f4.txt f6.txt
FILES=($(ls /path/to/*.txt | grep -wv '^manifest.txt$'))
touch 'this * is * a * file.txt' manifest.txt
命令创建文件,然后使用此方法并查看FILE
数组包含的内容。 - Gordon Davissontouch
命令,然后运行您的命令(在 $PWD/*.txt
上),然后运行 printf "'%s' " "${FILES[@]}"
,会给我返回 '/Users/gordon/tmp/manifest.txt' '/Users/gordon/tmp/this' 'manifest.txt' 'this * is * a * file.txt' 'is' 'manifest.txt' 'this * is * a * file.txt' 'a' 'manifest.txt' 'this * is * a * file.txt' 'file.txt'
。 - Gordon Davisson
!(manifest).txt
的数组。我认为你需要除了extglob
之外还要使用nullglob
。 - Fredextglob
?请注意,它可以在交互式 shell 中打开,但在非交互式 shell 中关闭,以防你尝试在脚本中使用。我认为不需要nullglob
。 - Benjamin W.nullglob
(其他没有更改),我就从预期的结果转变为我的评论中描述的结果。 - Fred.txt
文件的情况下呢?那是我能理解你所描述的唯一方式。 - Benjamin W..txt
文件;也许这种情况应该明确处理? - Fred