Skip to content

Instantly share code, notes, and snippets.

@bahamas10
Created November 12, 2013 21:46
Show Gist options
  • Select an option

  • Save bahamas10/7439354 to your computer and use it in GitHub Desktop.

Select an option

Save bahamas10/7439354 to your computer and use it in GitHub Desktop.
array counting in bash #bash@freenode
dave @ [ bahamas10 :: (Darwin) ] ~/temp/hash $ shasum *
e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e  a
e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e  b
7448d8798a4380162d4b56f9b452e2f6f9e24e7a  c
adfd3eb8f284fe13079be0a1a0a78c6bd1fd8a67  count.sh

file a and b are the same

dave @ [ bahamas10 :: (Darwin) ] ~/temp/hash $ ./count.sh 
./a        hash found 2  times
./b        hash found 2  times
./c        hash found 1  times
./count.sh hash found 1  times
#!/usr/bin/env bash
# count how many times $1 appears in an array
count() {
local needle=$1 i=0 hay
shift
for hay in "$@"; do
[[ $needle == $hay ]] && ((i++))
done
echo "$i"
}
# build an array of hashes found, may contain duplicates
hashes=()
for f in ./*; do
hash=$(shasum < "$f" | awk '{print $1}')
hashes=("${hashes[@]}" "$hash")
done
# loop each file again, and count how many times its hash was found
for f in ./*; do
hash=$(shasum < "$f" | awk '{print $1}')
count=$(count "$hash" "${hashes[@]}")
printf '%-10s hash found %-2d times\n' "$f" "$count"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment