Search code examples
grepls

get filenames with paths that match a basename pattern


I have a list of filenames with their paths like this

/some/path/or/another/RCrandomname.TRI
/another/path/NCrandomname2.TRI
/one/more/path/RCrandomname3.PCD

I would like to pick only the filenames (with their paths) whose basename starts with RC and have extension TRI so in the above example I would like to get just

/some/path/or/another/RCrandomname.TRI

if I had the basename only I could do

ls | grep "^RC.*\.TRI$" > filenames

but here I have all the paths. I have a requirement of using ls


Solution

  • Don't parse output of ls, it is error prone in many ways.

    You can use globbing with shopt globstar:

    shopt -s globstar
    ls -1 **/RC*.TRI > filenames
    

    globstar, When enabled, the globbing code treats ** specially -- it matches all directories (and files within them, when appropriate) recursively.