Is it possible to check whether a file exists with regular expression in bash?
I tried as follows:
if [ -f /path/to/file*.txt ]
But unfortunately this does not work.
Does anyone know how this is possible?
Is it possible to check whether a file exists with regular expression in bash?
I tried as follows:
if [ -f /path/to/file*.txt ]
But unfortunately this does not work.
Does anyone know how this is possible?
Your approach would work as long as there is exactly one file that matches the pattern. bash expands the wildcard first, resulting in a call like:
if [ -f /path/to/file*.txt ]
if [ -f /path/to/file1.txt ]
if [ -f /path/to/file1.txt /path/to/file2.txt ]
depending on the number of matches (0, 1, 2, respectively). To check just for the existence, you might just use find:
find /path/to -name 'file*.txt' | grep -q '.'
As @thiton explains the glob
(not a real regexp) is expanded and the check fails when multiple files exists matching the glob.
You can exploit instead compgen
as explained here
Test whether a glob has any matches in bash
Read more on the man page of compgen
Here is an example
if $(compgen -G "/path/to/file*.txt" > /dev/null); then
echo "Some files exist."
fi