0

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?

cheersmate
  • 2,385
  • 4
  • 19
  • 32
  • 1
    If you can use find to get all files with 4 character long names, and use it to get all files with 5 character long names... well... it does have an or operator that would let you get both. – Shawn Aug 10 '18 at 05:37
  • Is there a better way of doing than using two finds with an operator in between? – OpenSourceEnthusiast Aug 10 '18 at 05:39
  • 1
    It only takes one find invocation... – Shawn Aug 10 '18 at 05:42
  • Please avoid *"Give me the codez"* questions. Instead show the script you are working on and state where the problem is. Also see [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/608639) – jww Aug 10 '18 at 07:23
  • @jww You didn't read the question carefully. OP did write a `find` command (it's just not formatted correctly). – oliv Aug 10 '18 at 07:41
  • do not forget to accept answer that helped you the most –  Apr 25 '21 at 16:23

3 Answers3

3

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$'
2
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
PesaThe
  • 7,259
  • 1
  • 19
  • 43
0

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.

oliv
  • 12,690
  • 25
  • 45