Quantcast
Viewing all articles
Browse latest Browse all 6

The Command Line Utility “jot”

My good friend Kenny Chiou, a physical anthropology graduate student at Washington University in St. Louis, sent me a handy script he wrote to generate a series of number in R after seeing my previous blog post. Talking to him reminded me of the command line utility jot, which seems to be only on Macs and a subset of Unix machines. It’s a handy one to have in your toolkit, so here’s a brief tutorial.

jot with one number after it gives you a sequence up to the supplied number starting with one:

$ jot 5
1
2
3
4
5

Adding a second number lets you change the start, so here are five numbers starting with 50:

$ jot 5 50
50
51
52
53
54

If you use it as the input for a for loop, you can embed your number series in echoed text:

$ for i in `jot 5 50`; do echo "img${i}.jpg"; done;
img50.jpg
img51.jpg
img52.jpg
img53.jpg
img54.jpg

which actually can be more simply done using the -w flag and sprintf string formatting:

$ jot -w "img%d.jpg" 5 50
img50.jpg
img51.jpg
img52.jpg
img53.jpg
img54.jpg

And since it uses sprintf formatting, you can add leading zeros simply by changing the %d to, say %03d for three digits:

$ jot -w "img%03d.jpg" 5 50
img050.jpg
img051.jpg
img052.jpg
img053.jpg
img054.jpg

I wrote a script to rip off Kenny’s idea duplicate the functionality of Kenny’s script using pure bash. It gets passed parameters, computes the total length of the desired sequence, and then calls jot similar to the last example command above. You call it like this:

get_sequence -b beginning -e ending -p prefix -s suffix [-d digits]

$ ./get_sequence -b 17 -e 24 -p "img" -s ".png"
img17.png
img18.png
img19.png
img20.png
img21.png
img22.png
img23.png
img24.png

Here’s the full script, quick and dirty and untested. It could be useful to stick in your bin/ directory. All credit to Kenny for the inspiration and algorithm.

#!/bin/bash
# Arguments = -b beginning -e ending -p prefix -s suffix [-d digits]

# Default values
begin=1;
end=10;
digits=1;

while getopts b:e:p:s:d: opt; do
	case $opt in
		b) begin=$OPTARG;;
		e) ending=$OPTARG;;
		p) prefix=$OPTARG;;
		s) suffix=$OPTARG;;
		d) digits=$OPTARG;;
	esac
done

total=`expr $ending - $begin`
total=`expr $total + 1`

jot -w "$prefix%0${digits}d${suffix}" $total $begin;

exit;

Edit: Aaannnnd thanks to Kenny for catching a bug in the script.


Viewing all articles
Browse latest Browse all 6

Trending Articles