我正在尝试创建一个脚本,该脚本获取扩展名并在两列中报告用户和用户拥有的具有该扩展名的文件数量。 结果必须打印在report.txt中
这是我的代码。
#!/bin/bash
#Uncoment to create /tmp/test/ with 50 txt files
#mkdir /tmp/test/
#touch /tmp/test/arch{01..50}.txt
clear
usage(){
echo "The script needs an extension to search"
echo "$0 <extension>"
}
if [ $# -eq 0 ]; then
usage
exit 1
fi
folder="/tmp/test/"
touch report.txt
count=0
pushd $folder
for file in $(ls -l); do
grep "*.$1" | cut -d " " -f3 >> report.txt
done
popd
程序会不停地运行。而且我什至没有计算每个用户的文件数。 如何仅使用 grep 和 cut 来解决这个问题?
最佳答案
使用 GNU stat
:
stat -c '%U' *."$1" | sort | uniq -c | awk '{print $2,"\t",$1}' > report.txt
正如 mklement0 所指出的,在 BSD/OSX 下,您必须使用 -f
选项和 stat
:
stat -f '%Su' *."$1" | sort | uniq -c | awk '{print $2,"\t",$1}' > report.txt
编辑:
要处理许多文件并避免参数数量限制,您最好使用通过管道传输到 stat
命令的 printf
(再次感谢 mklement0):
printf '%s\0' *."$1" | xargs -0 stat -c '%U' | sort | uniq -c | awk '{print $2,"\t",$1}'
关于bash - 使用 cut 和 grep 进行报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38273999/