3

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?

terdon
  • 242,166
Richard
  • 39
  • 1
  • 2

3 Answers3

6

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"}'

steve
  • 21,892
5

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
shalomb
  • 197
2

Something like ls | sed -e 's/\.[0-9]\+$//' | sort | uniq -c should do what you want.

user2233709
  • 1,669