We use a numeric version control for files (ex: report01.log.01, report01.log.02, report01.log.03, etc.)
What I need to do is produce a list each file and the number of versions the file has.
Does Linux has a function to do this relatively easily?
We use a numeric version control for files (ex: report01.log.01, report01.log.02, report01.log.03, etc.)
What I need to do is produce a list each file and the number of versions the file has.
Does Linux has a function to do this relatively easily?
Another approach : ls | cut -f1 -d. | uniq -c
.
awk
approach : ls | awk -F. '{a[$1]++}END{for(b in a){print b,a[b]}}'
(long winded) perl
approach : ls|perl -e 'while(<>){$a{(split(/\./,$_))[0]}++}for(sort keys %a){print "$_ $a{$_}\n"}'
I'd advise against parsing the output of ls
, find
, etc (see ParsingLs - Greg's Wiki for an explanation of why that's a bad idea).
Instead, Parameter Expansion on a bash array can produce a list without the file extensions.
filelist=(*); # or filelist=(*.log.*) to be more precise
printf '%q\n' "${filelist[@]%.*}" # or echo "${filelist[@]%.*}"
Then, to work on the files individually ..
for i in "${filelist[@]%.*}"; do
echo "$i";
done
For OP's particular purpose, we can use a bash associative array to hold the count of versions.
filelist=(*.log.*)
declare -A count
for i in "${filelist[@]%.*}"; do
(( count["$i"]++ ));
done
for j in "${!count[@]}"; do
printf '%q\t%q\n' "$j" "${count[$j]}";
done | sort
report01.log 6
report02.log 6
report03.log 6
report04.log 6
report05.log 6
Something like ls | sed -e 's/\.[0-9]\+$//' | sort | uniq -c
should do what you want.
ls
, so I’d rather recommend his solution than mine or steve’s.
– user2233709
Apr 17 '17 at 20:43