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?
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?
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$'
shopt -s extglob globstar
printf '%s\n' **/?????(?).tgz
extglob
: enables extended globbingglobstar
: **
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 patternsOr simply:
printf '%s\n' **/????.tgz **/?????.tgz
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.