Bartosz
Bartosz

Reputation: 1594

Search a directory for files with fixed name pattern

I want to search a directory (let's call it "testDir") for files which names start with a letter "a", have letter "z" at fourth position and their file extension is .html.

Is there any way to use grep for this? How can I search for a character at fixed index?

Upvotes: 1

Views: 134

Answers (2)

janos
janos

Reputation: 124646

You can use native Bash pattern matching: a??z*.html. This pattern means exactly what you're asking for:

  • Start with the letter "a"
  • Followed by any two characters
  • Followed by the letter "z" (4th position)
  • Followed by 0 or more characters
  • Ending with ".html"

You can get the matching filenames with any shell tool that prints filenames when passed as arguments. Some examples:

  • ls testDir/a??z*.html or echo testDir/a??z*.html. Note that these will print with the testDir/ prefix.
  • (cd testDir && echo a??z*.html) will print just the filenames without the testDir/ prefix.
  • Note that the ls command will produce an error when there are no matching files, while the echo command will print the pattern (a??z*.html).

For more details on pattern matching, see the Pattern Matching section in man bash.

If you are looking for an alternative that produces no output when there are no matches, grep will be easier to use, but grep uses different syntax for matching pattern, it uses regular expressions. The same pattern written in regular expressions is ^a..z.*\.html$. This breaks down to:

  • ^ means start of line, so ^a means to start with "a"
  • . is any character, precisely one
  • .* is 0 or more of any character
  • \. is a "."
  • $ means end of line, so html$ means to end with "html"

Here's one way to apply it to your example:

(cd testDir && ls | grep '^a..z.*\.html$')

Upvotes: 1

Ophelia
Ophelia

Reputation: 36

How about this:

ls -d testDir/a??z* |grep -e '.html$'

Upvotes: 0

Related Questions