Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reporting with cut and grep

Tags:

grep

bash

shell

cut

I'm trying to create a script that gets an extension and reports in two columns, the user and the amount of files that user owns with that extension. The results must be printed in report.txt

Here is my code.

#!/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

The program just runs endlessly. And I'm not even counting the files for each user. How can I solve this using only grep and cut?

like image 258
Telefang Avatar asked Mar 07 '26 19:03

Telefang


1 Answers

With GNU stat :

stat -c '%U' *."$1" | sort | uniq -c | awk '{print $2,"\t",$1}' > report.txt

As pointed out by mklement0, under BSD/OSX you must use a -f option with stat :

stat -f '%Su' *."$1" | sort | uniq -c | awk '{print $2,"\t",$1}' > report.txt

Edit :

To process many files and avoid argument number limitation, you'd better use a printf piped to the stat command (thanks again mklement0) :

printf '%s\0' *."$1" | xargs -0 stat -c '%U' | sort | uniq -c | awk '{print $2,"\t",$1}'
like image 98
SLePort Avatar answered Mar 10 '26 14:03

SLePort