Check If a File Exists Using a Wildcard

Check if a file exists with a wildcard in a shell script

For Bash scripts, the most direct and performant approach is:

if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
echo "pattern exists!"
fi

This will work very speedily even in directories with millions of files and does not involve a new subshell.

Source


The simplest should be to rely on ls return value (it returns non-zero when the files do not exist):

if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi

I redirected the ls output to make it completely silent.


Here is an optimization that also relies on glob expansion, but avoids the use of ls:

for f in /path/to/your/files*; do

## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"

## This is all we needed to know, so we can break after the first iteration
break
done

This is very similar to grok12's answer, but it avoids the unnecessary iteration through the whole list.

bash check if a given file exists in a directory is failing on wildcard

Wildcard will give you a list.

Using bash:

exist_files() {
ext="${1}"
for file in *."${ext}"; do
[[ -f $file ]] && return 0
done
return 1
}

if exist_files "tf"; then
echo "File matching *.tf exists"
else
echo "File matching *.tf doesn't exists"
fi

Check if file exists using full paths and wildcard for filename bash

[ -n "$(find /path/to/data/dir -name '*20171101*' | head -1)" ] && ...

The quoting is important to prevent the shell from expanding it in the current directory. You need to use test -n because find alone won't tell you if it found matches or not. The head -1 stops when it finds a match, so you don't waste time looking for more.

Check if a file exists using a wildcard

Your wildcard would refer to a set of files, not a single file. You could use Dir::glob for this:

!Dir.glob('/folderOfFile/Filename*.ext').empty?

Perl: check existence of file with wildcard

Why not use glob() for that?

if (my @files = glob("\Q$name\E_file_*.txt")) {
# do something
}

How to check if file exists using wildcard * in Erlang?

You should use filelib:wildcard/1,2

Check for existence of file with wildcard-expansion in R

Re-read the question and now have a better understanding of what is required, please try:

path_root <- "C:/Users/User/Documents"
variable <- c("somepattern.*", ".*R")
#Search for pattern in directories:
grepl(paste(file.path(path_root, variable), collapse = "|"), list.dirs(path_root, full.names = TRUE, recursive = FALSE))


Related Topics



Leave a reply



Submit