Search code examples
bashls

bash list files of a particular naming convention


Operating System - Linux (Ubuntu 20.04)

I have a directory with thousands of files in it. The file names range anything from a.daily.csv to a.b.daily.csv to a.b.c.daily.csv to a.b.c.d.daily.csv to a.b.c.d.e.daily.csv

The challenge I'm having is in listing just a.daily.csv or a.b.daily.csv and so on. That is to say with "daily.csv" as the fixed part, I would like to be able to wildcard what is in front of it with "." being the delimiter between the fields

I tried a few wildcards such as ? [a-zA-Z0-9] & so on but unable to achieve this. Please could I get some guidance

Please note a,b,c etc are placeholders I'm using to post the question. In real world, a,b,c are alphanumeric words

Example -

PAHKY.daily.csv
TYUI.GHJ.WE.daily.csv
WGGH.FGH.daily.csv
98KJL-GHR.YUI.daily.csv
67HJE.HJQ.ATD.HJ.daily.csv

If I want to list all those files that are like PAHKY.daily.csv where thre is only one filed (dot being the delimiter) in front of daily.csv, how could I do this?


Solution

  • If you enable the extglob option:

    $ shopt -s extglob
    

    you can use extended pattern matching operators like *(pattern) for zero or more of pattern. Knowing that [^.] matches any character but a dot, this leads to:

    $ ls *([^.]).daily.csv
    PAHKY.daily.csv
    

    to obtain all a.daily.csv files. For the next group:

    $ ls *([^.]).*([^.]).daily.csv
    WGGH.FGH.daily.csv  98KJL-GHR.YUI.daily.csv
    

    and so on. Replace *(pattern) by +(pattern) if you want to match one or more of pattern instead of zero or more.