2

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}'
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Ram
  • 383
  • 4
  • 5
  • 12

2 Answers2

7

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}'`
dchirikov
  • 3,818
  • 2
  • 15
  • 18
2

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:

Joseph R.
  • 38,849
  • 7
  • 107
  • 143
  • `-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
  • 1. Solutions using `ls` and `awk` mis-fire on files that contain the current month abbreviation in the name, e.g. "Octopus", "Nova", "Decimal", etc. 2. Solutions using `ls` and `awk` fail to print the full name of files that contain blanks or newlines in the name, e.g. "my file". 3. As has been said: do not [parse the output of ls](http://mywiki.wooledge.org/ParsingLs). Use `find`. – Ian D. Allen Oct 15 '13 at 15:00