In Bash, given a sequence of files File.Number.{1..100}.txt, how can I tell which do not exist in a given directory
(Your question says "files that do exist" in one place, and "files that don't" in another, so I wasn't sure which one you wanted.)
To get the ones that do exist, you could use an extended glob in Bash:
$ 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
The shopt -s nullglob
enables bash's nullglob
option so that nothing is returned if there are no files matching the glob. Without it, a glob with no matches expands to itself.
Or, more simply, a numeric range in Zsh:
% echo File.Number.<1-10>.txt
File.Number.10.txt File.Number.1.txt File.Number.7.txt File.Number.9.txt
It's not like the loop is that bad either, and lends to finding the files that do not exist much better than a 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
Just use ls File.Number.{1..10}.txt >/dev/null
Example below.
$ 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
$
In zsh
, to reduce a list to the elements that refer to existing entries in a given directory, you could do:
dir=/some/dir
list=(File.Number.{1..10}.txt other-file-{a,b}.txt)
existing_in_dir=($dir/$^list(N:t))
non_existing=(${list:|existing_in_dir})