Search code examples
shellunixlsmetacharacters

How can I get a long listing of text files containing "foo" followed by two digits?


Using metacharacters, I need to perform a long listing of all files whose name contains the string foo followed by two digits, then followed by .txt. foo**.txt will not work, obviously. I can't figure out how to do it.


Solution

  • Use Valid Shell Globbing with Character Class

    To find your substring anywhere in a filename like bar-foo12-baz.txt, you need a wilcard before and after the match. You can also use a character class in your pattern to match a limited range of characters. For example, in Bash:

    # Explicit character classes.
    ls -l *foo[0-9][0-9]*.txt
    
    # POSIX character classes.
    ls -l *foo[[:digit:]][[:digit:]]*.txt
    

    See Also