bash - 使用 cut 和 grep 进行报告

标签 bash shell grep cut

我正在尝试创建一个脚本,该脚本获取扩展名并在两列中报告用户和用户拥有的具有该扩展名的文件数量。 结果必须打印在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/

相关文章:

linux - 当文本行出现在文件中时如何使用 Bash 做一些事情

linux - 从脚本获取要安装的软件包列表?

linux - "root/.bashrc about: command not found"

bash - 在 sed 中使用变量

linux - 如何通过 Linux shell 命令关闭文件描述符

java - 如何创建一个模拟 SSH shell 用户交互的机器人?

linux - 文件操作: removing every occurence of a string execpt the first occurence after a certain different pattern

perl - Grep -> 如何替换文本文件的内容

linux - 如果文件名作为变量传递,如何使用 diff 命令比较两个 tar 文件的内容

linux - 在 bash 中提取特定单词