How search for a file beginning with either a or z and ending with a or z?

16,948

Assuming I understood your question, you are possibly overcomplicating it. This should do

find your_directory -type f -name '[az]*[az]'

This omits files whose name is a single letter a or z. If you also want to include them, you need to specify another pattern: the name must match either [az]*[az] or [az].

find your_directory -type f \( -name '[az]*[az]' -o -name '[az]' \)
Share:
16,948

Related videos on Youtube

linux8807
Author by

linux8807

Updated on September 18, 2022

Comments

  • linux8807
    linux8807 over 1 year

    I attempted find -name 'a*' 'z*' '*a' '*z'

    but it gave me the error code find: paths must precede expression: z*

    I know how to find files starting with a though z, or ending with a-z, but not starting with specific letters.

    • Admin
      Admin over 10 years
      The error is because you can't combine multiple criteria this way. To specify that you want -name to be either a* or z*, you should say: -name 'a*' -o -name 'z*'. Of course 1_CR gave you the correct answer for your particular case.
  • Mathias Begert
    Mathias Begert over 10 years
    @Gilles, thank you for addressing the corner case
  • Matt
    Matt over 10 years
    find . '(' -name 'a*' -o -name 'z*' ')' -a '(' -name '*a' -o -name '*z' ')' is more similar to what @linux8807 was originally trying to express, and it also catches the corner case.
  • frostschutz
    frostschutz over 10 years
    Or find -name '[az]*' -a -name '*[az]'
  • linux8807
    linux8807 over 10 years
    Wouldn't find -name '[az]*' find files starting with az? That's how I interpreted that.
  • Mathias Begert
    Mathias Begert over 10 years
    @linux8807, find -name '[az]*' finds files starting with either a or z. Pattern matching with find is based on shell pattern matching, so if you can get it to work with the shell on the command line, it should work similarly with find
  • linux8807
    linux8807 over 10 years
    I'll be honest, I'm in school and the question my professor had for me was exactly "Now, suppose you want to list all the files in that same directory whose names start with a or z and end with a or z? " I've tried the answers given to me because I cannot find the help needed in my lessons or the Linux Bible. I first attempted with find ./directory '(' -name 'a*' -o -name 'z*' ')' -a '(' -name 'a' -o -name '*z' ')' which was considered incorrect them I attempted find ./directory -name '[az]' '*[az]' and still it was incorrect. Any ideas on what my professor could be asking for exactly?
  • Mathias Begert
    Mathias Begert over 10 years
    @linux8807, have you tried find -name '[az]*[az]'
  • Eduardo Lucio
    Eduardo Lucio over 5 years
    Another example based on @iruvar 's answer: find ./ -type f -name 'file_name*.ext'. Thanks! =D