Skip to content
Advertisement

Linux using date Command to subset files then count the files

I am using linux verison CentOS Linux 7 (Core).

I have files that look like this: NameofArea_year_dayofyear_input

For example: SanAntonio_2021_186_input

I would like to count how many files there are on yesterdays date. For example this works and counts my files

find . -name "*_2021_186_input*" | wc -l

I am trying to make -name flag in find use the date command

This date command

date -d '-1 day' +'*_%Y_%j_input*'

Would produce *_2021_186_input* Which I would like to go into the find

I would expect this to work but it does not.

Day=`date -d '-1 day' +'*_%Y_%j_input*'`

find . -name $Day | wc -l

In fact it seems when I examine echo $Day is a list of my file names which does not make sense to me. Does anyone know what I can do to fix this?

EDIT: Also I discovered when I do echo $Day in . where my files are located then it is a list of my file names. When I do echo $Day in a different directory then it is the output I expect. “*_year_dayofyear_input*”

Advertisement

Answer

Unquoted variable expansions undergo word splitting and filename expansion.

$ a='*'
$ set -x
$ echo *
+ echo file1.txt file2.txt ....
file1.txt file2.txt ....

When you put *something* in a variable and then unquoted $Day undergoes filename expansion, which expands it to list of paths before running the command.

$ Day='*_2021_186_input*'
$ find . -name $Day | wc -l
+ find . -name file1_2021_186_input file2_2021_186_input ...

You want to pass * literally to find. I see no reason to put * in day, just:

day=$(date -d '-1 day' +'_%Y_%j_input')
find . -name "*$day*" | wc -l

Check your scripts with shellcheck.net

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement