Search code examples
bashglob

How to print a list of regex matches using variables and asterisk


I have this list of files:

perspectium-02-16-2019-1.log.gz  perspectium-07-27-2019-3.log.gz  perspectium-10-18-2019-1.log.gz
perspectium-07-27-2019-1.log.gz  perspectium-10-16-2019-1.log.gz  perspectium-10-18-2019-2.log.gz
perspectium-07-27-2019-2.log.gz  perspectium-10-17-2019-1.log.gz  perspectium-10-18-2019-3.log.gz

I have calculated one date:

d=$(date -d '-1 day' '+%m-%d-%Y') 

I want to delete those files that matches the condition:

perspectium-$d-*.log.gz

But if I make an echo of this, it will print the asterisk literally, so It wont match any file:

perspectium-10-17-2019-*.log.gz

Can you please give me some clue? Thanks in advice.


Solution

  • You can use following:

    output=`ls perspectium-$d-*.log.gz`
    echo $output
    

    or

    for file in perspectium-$d-*.log.gz
    do
    echo $file
    done;
    

    or just do without quotes:

    echo perspectium-$d-*.log.gz
    

    But as already said, care about possible issues with incorrect matching.

    Here is output for you case:

    [root@pro-sip tmp]# d=10-18-2019
    [root@pro-sip tmp]# ls perspectium-$d-*.log.gz
    perspectium-10-18-2019-1.log.gz  perspectium-10-18-2019-2.log.gz
    [root@pro-sip tmp]# for i in  perspectium-$d-*.log.gz  
    > do
    > echo $i
    > done;
    perspectium-10-18-2019-1.log.gz
    perspectium-10-18-2019-2.log.gz
    [root@pro-sip tmp]# echo perspectium-$d-*.log.gz
    perspectium-10-18-2019-1.log.gz perspectium-10-18-2019-2.log.gz