Command Line Sequences
Sometimes, you have an ordered set of files to work - a common example may be numbered files in the format of 1.mp3, 2.mp3, … or even something like page001.png, page002.png, and so on. The seq
command makes working with these easy (and comes built in on Linux and macOS).
Why this Matters
Imagine having 1000 files numbered in order (page0001.png, page0002.png … page1000.png), and you want to add a page at the beginning that becomes page0001.png, and the remaining pages would move up accordingly - instead of moving 999 pages to increase their numbers, you can use a combination of seq
with a for loop as above to move these with relative ease.
For example:
for i in `seq -w 1 1000`; do
# the updated page is just i + 1, so page 1 will be 2, and so on
updated_page=$((i+1))
mv page$i.png page$updated_page.png
done
Usage
# prints 1 through 5
seq 1 5
# Output
# 1
# 2
# 3
# 4
# 5
# the second parameter is the amount to increment by if there are 3 parameters
seq 4 2 10
# Outputs
# 4
# 6
# 8
# 10
# backwards
seq 5 1
# Outputs
# 5
# 4
# 3
# 2
# 1
I recently learned that you can change the delimiter between the numbers using the -s
parameter.
seq -s, 1 5
# Outputs 1,2,3,4,5, <without a newline>
# pass -t \\n if you want a newline at the end
Two other useful flags are the -w
and the -f
flags. The -w
flag is an easy way to zero pad numbers to be the same width. this is really useful when say i have a list of page001.png, page002.png, … page100.png - by using seq -w 1 100
, I’ll get a list of 001, 002, … 100. The -f
flag is for the format to print numbers - so seq -f "%03g" 9 10
would output 009 and 010.
Note that aside from moving files (or aside from ordered collections of files), this is also useful for other things as well - for example, if you want to run an app changing parameters to see what gets the best output, you can generate that parameter with seq
. Also, seq
understand floating point, so seq 1 0.5 4
would output 1, 1.5, 2, 2.5, 3, 3.5, 4.