Linux: find file names with 4 or 5 characters

8.9k Views Asked by At

How can I find file names consisting of either 4 or 5 characters?

For file names with 4 characters, I can use find . -name ????.tgz, but how to I expand this to length either 4 or 5?

3

There are 3 best solutions below

2
On

Here is one solution:

find . \( -name "????.cpp" -o -name "?????.cpp" \)

-o is for logical OR

just replace .cpp with .tgz or whatever you want. There is also this regex version that would do the same thing:

find . -regextype posix-egrep -regex '^./[a-zA-Z]{4,5}\.cpp$'

in regex ^ is start symbol ^./ means starts with ./. [a-zA-Z]{4,5} means followed by 4 to 5 characters, \. means . where \ is escape character \.cpp$ means ends with .cpp

If file name contains numbers instead of [a-zA-Z] do [a-zA-Z0-9]. So it will look like this:

find . -regextype posix-egrep -regex '^./[a-zA-Z0-9]{4,5}\.cpp$'
0
On

You could use this find command:

find -type f -regextype egrep -regex ".*/[^./]{4,5}\.[^./]+$" 

The regular expression is set catch any basename file with 4 or 5 characters. Note this regex applies on the full name, including path.

0
On
shopt -s extglob globstar
printf '%s\n' **/?????(?).tgz
  • extglob: enables extended globbing
  • globstar: ** will match all files and zero or more directories and subdirectories
  • ?: matches any single character
  • ?(pattern-list): matches zero or one occurrence of the given patterns

Or simply:

printf '%s\n' **/????.tgz **/?????.tgz