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

ls -l | awk -v d="$Date" '/d/ {print $NF}'
  • You have not explained what you really want. This is a broken code. – Valentin Bajrami Oct 15 '13 at 12:09
  • 2
    May be it's better to use find with -mtime? – dchirikov Oct 15 '13 at 12:29
  • @dchirikov Agreed, or even -ctime to catch when file attributes have changed. – Joseph R. Oct 15 '13 at 12:43

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:

  • -v tells awk to use environmental variable – dchirikov Oct 15 '13 at 12:24
  • @dchirikov As far as I know, -v is used to assign variables localized to awk not obtain variables from your current environment. – Joseph R. Oct 15 '13 at 12:42
  • 2
    Right. Environment variables can be accessed through the 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
  • yep! ENVIRON of course. And -v is for shell variables. – dchirikov Oct 15 '13 at 12:57
  • 1
    @Ram Glad I helped. I believe dchirikov's answer was better though. Stay away from the output of ls unless you're parsing it with your eyes. – Joseph R. Oct 15 '13 at 14:48

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}'`
  • +1 I hope you don't mind, I edited your link so that it points directly to the relevant section instead of the TOC. – Joseph R. Oct 15 '13 at 13:00
  • Since I am using AIX 6.1 machine the flags such as -maxdepth and -daystart are not available. – Ram Oct 15 '13 at 13:34
  • Ok. I've added an update. Hope it helps. – dchirikov Oct 15 '13 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.