Skip to content

Instantly share code, notes, and snippets.

@zemm
Last active April 22, 2021 23:12
Show Gist options
  • Save zemm/e23691ac34512f12ac916e4b5fbacf8b to your computer and use it in GitHub Desktop.
Save zemm/e23691ac34512f12ac916e4b5fbacf8b to your computer and use it in GitHub Desktop.
Show files missing from a sequence

Show files missing from a sequence

First let's have a broken sequence of files:

➜ touch page-{1,2,5}.jpg

➜ ls
page-1.jpg  page-2.jpg  page-5.jpg  show-missing.sh

"What was I missing again?"

➜ ls *.jpg | ./show-missing.sh 
page-3.jpg
page-4.jpg

"But some of my numbers are padded with zeroes!"

➜ mv page-1.jpg page-01.jpg

➜ mv page-5.jpg page-005.jpg

➜ ls *.jpg | ./show-missing.sh 
page-3.jpg
page-4.jpg

Divergent patterns confuse us :( Better to admit to a defeat than to be ambiguous.

➜ touch foobar666.jpg

➜ ls *.jpg | ./show-missing.sh
Abort! Divergent naming patterns found: 'foobar#.jpg' vs 'page-#.jpg'

➜ ls page-*.jpg | ./show-missing.sh
page-3.jpg
page-4.jpg

➜ rm foobar666.jpg

"But I want my sequences to start from zero!"

➜ ls page*.jpg | ./show-missing.sh 0
page-0.jpg
page-3.jpg
page-4.jpg

"But I only like sequences of 3 to 7!"

➜ ls page*.jpg | ./show-missing.sh 3 7 
page-3.jpg
page-4.jpg
page-6.jpg
page-7.jpg
#!/usr/bin/env bash
# @TODO:
# - handle two numbers: foo123bar456.txt
# - handle negative numbers
# - handle leading zeros on missing list (lol nope)
start_from="${1:-1}"; shift
end_to="${1:0}"; shift
all=";"
pattern=""
while IFS= read -r file; do
num=$(echo $file | sed -nEe 's/[^1-9]*([0-9]+).*/\1/p')
if [[ -n $num ]]; then
[[ $num -gt $end_to ]] && end_to=$num
all="$all$num;"
ptrn=$(echo $file | sed -Ee 's/([^0-9]*)[0-9]+(.*)/\1#\2/')
if [[ -n "$pattern" ]] && [[ "$pattern" != "$ptrn" ]]; then
>&2 echo "Abort! Divergent naming patterns found: '$pattern' vs '$ptrn'"
exit 2
fi
pattern="$ptrn"
fi
done
for i in $(seq "$start_from" "$end_to"); do
[[ "$all" != *";$i;"* ]] && echo "$pattern" | sed "s/#/$i/" || :
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment