-1

I am working on a task for which AWK is the designated tool.

The task is to list files that are:

  • modified today (same day the script is run)
  • of size 1 MB or less (size <= 1048576 bytes)
  • User's input is to instruct where to start search.
  • Search for files recursively.

Script:

#!/bin/bash

#User's input target for search of files.
target="$1"

#Absolute path of target.
ap="$(realpath $target)"
echo "Start search in: $ap/*"

#Today's date (yyyy-mm-dd).
today="$(date '+%x')"

#File(s) modified today.
filemod="$(find $target -newermt $today)"

#Loop through files modified today. 
for fm in $filemod
do
    #Print name and size of file if no larger than 1 MiB.
    ls -l $fm | awk '{if($5<=1048576) print $5"\t"$9}'
done

My problem is that the for-loop does not mind the size of files!

Every variable gets its intended value. AWK does what it should outside a for-loop. I've experimented with quotation marks to no avail.

Can anyone tell what's wrong?

I appreciate any feedback, thanks.

Update: I've solved it by searching explicitly for files:

filemod="$(find $target -type f -newermt $today)"

How come that matters?

henrix
  • 1
  • 3
  • Hi, I've got the desired result after searching for files explicitly: filemod="$(find $target -type f -newermt $today)" How come that matters? – henrix Mar 25 '17 at 16:17

1 Answers1

2

Don't parse 'ls' output. Use stat instead, like this:

for fm in $filemod; do
  size=$(stat --printf='%s\n' "$fm")
  if (( size <= 1048576)); then
    printf "%s\t%s\n" "$size" "$fm"
  fi
done

The above method is not immune to files that have white spaces or wild cards in their name. To handle such files gracefully, do this:

while IFS= read -r -d '' file; do
  size=$(stat --printf='%s\n' "$file")
  if (( size <= 1048576)); then
    printf "%s\t%s\n" "$size" "$file"
  fi
done < <(find $target -newermt $today -print0)

See also:

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 2
    you can also use `-size` : `while IFS= read -r -d '' n; do printf '%q\n' "$n"; done < <(find . -type f -mtime -1 -size -1048576c -print0)` – Bertrand Martel Mar 22 '17 at 22:29
  • I appreciate your efforts. While I believe your solutions do the work better, AWK is a prerequisite for this task. – henrix Mar 23 '17 at 22:24