我正在处理AWK作为指定工具的任务。
任务是列出以下文件:
脚本:
#!/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
我的问题是for循环不介意文件的大小!
每个变量都会达到预期的价值。 AWK在for循环之外做它应该做的事情。我试过引号无济于事。
任何人都可以说出错了吗?
感谢任何反馈,谢谢。
更新: 我通过明确搜索文件来解决它:
filemod="$(find $target -type f -newermt $today)"
重要的是什么?
答案 0 :(得分:2)
Don't parse 'ls' output.请改用stat
,如下所示:
for fm in $filemod; do
size=$(stat --printf='%s\n' "$fm")
if (( size <= 1048576)); then
printf "%s\t%s\n" "$size" "$fm"
fi
done
上述方法不能免受名称中带有空格或外卡的文件的影响。要优雅地处理这些文件,请执行以下操作:
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)
另见: