Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'find' files containing an integer in a specified range (in bash)

Tags:

linux

find

bash

You'd think I could find an answer to this already somewhere, but I am struggling to do so. I want to find some log files with names like

myfile_3.log

however I only want to find the ones with numbers in a certain range. I tried things like this:

find <path> -name myfile_{0..67}.log #error: find: paths must precede expression
find <path> -name myfile_[0-67].log #only return 0-7, not 67
find <path> -name myfile_[0,67].log #only returns 0,6,7
find <path> -name myfile_*([0,67]).log # returns only 0,6,7,60,66,67,70,76,77

Any other ideas?

like image 251
Ben Farmer Avatar asked Aug 17 '18 10:08

Ben Farmer


People also ask

How do I find a file with a specific pattern in Linux?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in.

How do you grep a range of numbers?

(1[0-9]|20)" . Your regular expression in grep asks for 1 or 2, and 2 or 0. 1[0-9] will match anything between 10 to 19 as well as 20. Save this answer.


2 Answers

If you want to match an integer range using regular expression, use the option -regex in the your find command.

For example to match all files from 0 to 67, use this:

find <path> -regextype egrep -regex '.*file([0-5][0-9]|6[0-7])\.txt'

There are 2 parts in the regex:

  • [0-5][0-9] matches the range 0-59
  • 6[0-7] matches the range 60-67

Note the option -regextype egrep to have extended regular expression.
Note also the option -regex matches the whole filename, including path, that's the reason of .* at the beginning of the regex.

like image 75
oliv Avatar answered Sep 28 '22 15:09

oliv


You can do this simply and concisely, but admittedly not very efficiently, with GNU Parallel:

parallel find . -name "*file{}.txt" ::: {0..67}

In case, you are wondering why I say it is not that efficient, it is because it starts 68 parallel instances of find - each looking for a different number in the filename... but that may be ok.

like image 25
Mark Setchell Avatar answered Sep 28 '22 16:09

Mark Setchell