My goal is to get the file created in the current month in a directory.
It seems that the command is correct but not rendering any result:
Date=`date '+%b'`
echo $Date
Oct
ls -l | awk -v d="$Date" '/d/ {print $NF}'
My goal is to get the file created in the current month in a directory.
It seems that the command is correct but not rendering any result:
Date=`date '+%b'`
echo $Date
Oct
ls -l | awk -v d="$Date" '/d/ {print $NF}'
You should use it this way:
ls -l | awk -v d="$Date" '$0 ~ d {print $NF}'
Explanation is here
But may be it's better to use find
in your script.
find . -maxdepth 1 -type f -daystart -ctime -`date "+%d"`
If you have classic awk
instead of gawk
:
find * -prune -type f -cmin -`date '+%d %H %M' | awk '{print ($1*24+$2)*60+$3}'`
The problem here is that awk
has no way of telling that the d
inside the pattern is meant to represent the variable of that name: awk
is trying to match a literal d
. You can make use of parameter expansion instead:
ls -l | awk "/$Date/ {print \$NF}"
That said, two things to note:
The time listed in ls -l
output is the timestamp: the last time the file was modified, not created. File creation times are unreliable at best and unavailable at worst.
You shouldn't parse the output of ls
Use find
instead, as in dchirikov's answer.
-v
is used to assign variables localized to awk
not obtain variables from your current environment.
– Joseph R.
Oct 15 '13 at 12:42
ENVIRON
array. So if you previously export Date
, then ls -l | awk '$0 ~ ENVIRON["Date"] {print $NF}'
will also work.
– manatwork
Oct 15 '13 at 12:48
ls
unless you're parsing it with your eyes.
– Joseph R.
Oct 15 '13 at 14:48
ls
and awk
mis-fire on files that contain the
current month abbreviation in the name, e.g. "Octopus", "Nova",
"Decimal", etc.ls
and awk
fail to print the full name of files that
contain blanks or newlines in the name, e.g. "my file".find
.
find
with-mtime
? – dchirikov Oct 15 '13 at 12:29-ctime
to catch when file attributes have changed. – Joseph R. Oct 15 '13 at 12:43