2

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?

random
  • 9,774
  • 10
  • 66
  • 83
Kolesar
  • 1,265
  • 3
  • 19
  • 41

2 Answers2

5

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 '.'
thiton
  • 35,651
  • 4
  • 70
  • 100
0

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
Kuzeko
  • 1,545
  • 16
  • 39