13
Apr

Neat Find Trick with Wildcards

Blasphemy! Originally, I had titled this post “Neat Find Trick with Regular Expressions”, but the use of brackets is not necessarily a regular expression. Turns out, it’s actually one type of wildcard character. So, the post title has been changed to “Neat Find Trick with Wildcards” to reflect this new knowledge (thanks Jim). Okay, onward…

This is one of those “how did I miss that while learning Linux” tips. You can use regular expressions (regex) wildcards in the terminal to simplify your life. For example, the find command can take advantage of this sorta thing. Say that you’re looking for all files ending with .c or .h. Instead of using the ‘find’ command twice, you can simply use “*.[ch]” to search for them. The brackets tell find to search for any single character within them. You can learn more about regular expressions here, wildcards here, but for now, let’s see this in action:

find . -type f -name "*.[ch]"

As expected, this will find all files that end in a .c or .h extension. Have fun!

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 1 Comment So Far

  • [email protected]
    April 14th, 2010 at 6:53 pm

    Here’s an email I received from Jim about the use of the term “Regular Expressions”:

    Hi Derek,

    Sorry to be pedantic, but the file matching expressions used by find and ls are not strictly “regularly expressions” – they are wildcards.
    See the wikipedia entry at

    http://en.wikipedia.org/wiki/Regular_expression

    Last para, before the contents…

    “Many modern computing systems provide wildcard characters in matching filenames from a file system. This is a core capability of many command-line shells and is also known as globbing. Wildcards differ from regular expressions in generally only expressing very limited forms of alternatives.”

    In fact Regex are far far more powerful, and I often run find like

    find . -type f | grep ‘.[ch]$’

    which would do in a regex what find does by globbing. In this case the globbing is a lot easier, but

    find . type f | grep -i “ansi”

    would find that file I’m sure I had about ANSI command strings but couldn’t remember if I’d capitalised ANSI or not – it outputs any filename with “ansi” (in any case) in the name.

    In fact GNU find has the options ‘-regex’ and ‘-iregex’ for actually doing regex matching on filenames (-iregex is the case insensitive version).
    But busybox’s find doesn’t have this, or earlier BSD versions.

    cheers
    Jim

Share your thoughts, leave a comment!