0

I'm trying to use ls -l and filter only the files that were lastly modified in the current month. I'm running: ls -l | awk '{if($6 == date +%b) print$0; and get a syntax error.

I've been looking everywhere on the internet for simple rules as to how to use quotes correctly in awk and in script bashing and I can't make sense out of it. I'm very confused about this even though I have experience with programming so a general answer regarding those issues would be far more appreciated than a specific answer that will deal with this specific case.

  • you'll get lots of advice about what you're currently doing, but it might be more productive if you explained what your end-goal (or at least next step) is with this list of files, as there might be better ways of achieving it. (Parsing ls output is unreliable) – Jeff Schaller Aug 25 '16 at 13:34
  • It's just some homework and experimenting with linux. The end goal is to filter the ls-l output the way i've asked. If there's a way to do it without awk i'll be happy to know but would still want to know how to do it using the date command as well. – PanthersFan92 Aug 25 '16 at 13:37
  • I was going to link this, on command substitution (which is what you'll need for the date command), and this for the parts about the different types of quotes. (3rd and 4th item). But I can't judge if they're non-confusing enough. – ilkkachu Aug 25 '16 at 13:46
4

You probably don't want to call date multiple times in your code; it's "constant" for the duration of the run. So we can set it before hand and pass it as a variable

eg

ls -l | awk -v month="$(date +%b)" '$6 == month { print }'

Note that this will fail if you have a file that's from this month but a year old (eg from August 2015) or in locales where month names contain spaces, or if there are file names that contain newline characters. Parsing the output of ls is fraught with peril

1

Try this loop as variation, then. It stores today's current month and year, then uses shell globbing (*) to get the list of files (like a ls -l would -- but not like an ls -al would), then uses the GNU-provided stat command to pull the modification time of each file and extract the month and year. If that month and year is the same as the current month and year, then execute an ls -ld on the file (the -d flag is to prevent unintended subdirectory listings when $f is a directory).

thisym=$(date +%Y-%m)
for f in *
do
  ym=$(stat -c %y -- "$f" | cut -d- -f1-2)
  if [ "$ym" = "$thisym" ]
  then
    ls -ld -- "$f"
  fi
done

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.