Last active
June 11, 2016 02:32
-
-
Save ckujau/5314921 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Christian Kujau <[email protected]> | |
# | |
# Zero-padding examples in Bourne shell | |
# Based on some wonderful examples from | |
# http://jonathanwagner.net/2007/04/zero-padding-in-bash | |
# | |
if [ -z "$2" ]; then | |
echo "Usage: `basename $0` (`awk '/^\t[a-z0-9]*\)$/' "$0" | xargs echo | sed 's/) /|/g'` [count]" | |
exit 1 | |
else | |
MODE="$1" | |
COUNT="$2" | |
fi | |
# How long to pad for? | |
w=${#COUNT} # expr length $COUNT | |
# echo $COUNT | awk '{print length}' | |
case $MODE in | |
bash4) | |
# Bash-4.0 needed for zero-padding with braces | |
# see http://tldp.org/LDP/abs/html/bashver4.html#BRACEEXPREF4 | |
if [ "${BASH_VERSINFO[0]}" -lt 4 ]; then | |
echo "Bash-4.0 needed!" | |
exit 1 | |
fi | |
# For some reason this is not working in non-interactive shells | |
w=`expr $w + 1` | |
echo {01..$COUNT} | fold -"$w" | |
;; | |
bash41) | |
# Bash-4.1 needed for "printf -v" | |
# see http://tldp.org/LDP/abs/html/bashver4.html#AEN21051 | |
if [ "${BASH_VERSINFO[0]}" -lt 4 -o "${BASH_VERSINFO[1]}" -lt 1 ]; then | |
f=`printf "%"$w"s"` | |
p=`printf "%s\n" "${f// /0}"` | |
else | |
p=`printf -v f "%"$w"s"; printf "%s\n" "${f// /0}"` | |
fi | |
x=1 | |
while [ $x -le $COUNT ]; do | |
echo ${p:${#x}}$x | |
x=$((x+1)) | |
done | |
;; | |
printf) | |
x=1 | |
while [ $x -le $COUNT ]; do | |
printf "%0"$w"d\n" $x | |
x=$((x+1)) | |
done | |
;; | |
seq) | |
# Maybe seq(1) is installed as GNU seq? | |
seq --help > /dev/null 2>&1 && SEQ=seq | |
gseq --help > /dev/null 2>&1 && SEQ=gseq | |
$SEQ -w 1 $COUNT 2>/dev/null || echo "seq(1) from coreutils needed!" | |
;; | |
*) | |
echo "hm?" | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment