Tuesday, September 22, 2009

Kgggghhhhaaaa!!! seq is MISSING!

Seems that jot is the replacement (and is more powerful) but has a different syntax.

Derived from:

http://codesnippets.joyent.com/posts/show/1797

http://www.labrat.info/blog/?p=9



Add this function to your ~/.bash_profile

to rewrite your simple seq calls as jot.



# integer test

function is_int() { return $(test "$@" -eq "$@" >/dev/null 2>&1); }



function seq() {

declare incr n1 n2 num1 num2

if [[ $# -eq 1 ]]; then

if ! $(is_int "$1"); then echo 'No integer!'; return 1; fi

for ((i=1; i<=${1}; i++)) { printf "%d\n" ${i}; }

elif [[ $# -eq 2 ]]; then

if ! $(is_int "$1") || ! $(is_int "$2"); then echo 'Not all arguments are integers!'; return 1; fi


if [[ $1 -eq $2 ]]; then

echo $1

elif [[ $2 -gt $1 ]]; then

for ((i=${1}; i<=${2}; i++)) { printf "%d\n" ${i}; }

elif [[ $1 -gt $2 ]]; then

for ((i=${1}; i>=${2}; i--)) { printf "%d\n" ${i}; }

fi


elif [[ $# -eq 3 ]]; then

num1=${1}

incr=${2}

num2=${3}

#/usr/bin/awk -v n1=${num1} -v n2=${num2} -v add=${incr} 'BEGIN{ for(i=n1; i<=n2; i+=add) print i;}' | /usr/bin/sed 's/.+e.+/0/'

/usr/bin/awk -v n1=${num1} -v n2=${num2} -v add=${incr} 'BEGIN{ for(i=n1; i<=n2; i+=add) print i;}' | /usr/bin/sed -E '/e/s/^.+e.+$/0/'

fi

return 0

}







-------------------------------------------------------------------------------------

UPDATED VERSION

-------------------------------------------------------------------------------------



function seq() {

# rewrites seq as jot for osx with format support.

# Updated version by G. Facciolo


if [ $# -gt 0 ]

then

if [ $1 == "-f" ]

then # with format parameters start from 3

format=$2

case $# in

3) # single argument

jot -w $format $3

return 0;

;;

4) # double argument

let nr="2*($4-$3)"

jot -w $format $nr $3 $4 1

return 0;

;;

5) # triple argument

let nr="2*($5-$3)/$4";

jot -w $format $nr $3 $5 $4

return 0;

;;

esac

else # without format parameters start from 1

format=""

case $# in

1) # single argument

jot $1

return 0;

;;

2) # double argument

let nr="2*($2-$1)";

jot $nr $1 $2 1

return 0;

;;

3) # triple argument

let nr="2*($3-$1)/$2";

jot $nr $1 $3 $2

return 0;

;;

esac

fi

else

echo "seq to jot for osx by G. Facciolo"

echo "Usage: seq [-f format] LAST"

echo " or: seq [-f format] FIRST LAST"

echo " or: seq [-f format] FIRST INCREMENT LAST"

return 1;

fi



}


-------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------



No comments:

Post a Comment