我有一系列文件,如下所示:
File.Number.{1..10}.txt
Run Code Online (Sandbox Code Playgroud)
我想获取其中存在哪些文件的数组或序列。一种乏味的方法是遍历所有这些并附加到一个数组。我想知道是否有一个单行可以告诉我这些文件中哪些不存在或拉出文件的编号。
ilk*_*chu 13
(你的问题在一个地方说“确实存在的文件”,在另一个地方说“不存在的文件”,所以我不确定你想要哪个。)
要获得确实存在的那些,您可以在 Bash 中使用扩展的 glob:
$ shopt -s nullglob
$ echo File.Number.@([1-9]|10).txt
File.Number.10.txt File.Number.1.txt File.Number.7.txt File.Number.9.txt
Run Code Online (Sandbox Code Playgroud)
在shopt -s nullglob
使bash的nullglob
选项,因此,如果没有匹配的水珠文件返回,没有什么。没有它,没有匹配项的 glob 会扩展到自身。
或者,更简单地说,Zsh 中的数字范围:
% echo File.Number.<1-10>.txt
File.Number.10.txt File.Number.1.txt File.Number.7.txt File.Number.9.txt
Run Code Online (Sandbox Code Playgroud)
循环也不是那么糟糕,并且有助于查找不存在比 glob 好得多的文件:
$ a=(); for f in File.Number.{1..10}.txt; do [ -f "$f" ] || a+=("$f"); done
$ echo "these ${#a[@]} files didn't exist: ${a[@]}"
these 6 files didn't exist: File.Number.2.txt File.Number.3.txt File.Number.4.txt File.Number.5.txt File.Number.6.txt File.Number.8.txt
Run Code Online (Sandbox Code Playgroud)
只需使用 ls File.Number.{1..10}.txt >/dev/null
下面举例。
$ ls
File.Number.1.txt File.Number.3.txt
$ ls File.Number.{1..10}.txt >/dev/null
ls: cannot access 'File.Number.2.txt': No such file or directory
ls: cannot access 'File.Number.4.txt': No such file or directory
ls: cannot access 'File.Number.5.txt': No such file or directory
ls: cannot access 'File.Number.6.txt': No such file or directory
ls: cannot access 'File.Number.7.txt': No such file or directory
ls: cannot access 'File.Number.8.txt': No such file or directory
ls: cannot access 'File.Number.9.txt': No such file or directory
ls: cannot access 'File.Number.10.txt': No such file or directory
$
Run Code Online (Sandbox Code Playgroud)