brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: seq -w counts with leading zeros, so file names sort the right way

Linux
~/tips/tip-linux-seq-w-zero-padding

for i in $(seq -w 1 "$n"); do

Prints a number sequence with leading zeros, so numbered names line up and sort correctly.

Files called part-1 to part-10 sort as 1, 10, 2 in most listings, which drives me up the wall. seq can count with zeros in front, and unlike Bash’s {01..10} it takes the limits from variables.

-w (--equal-width) pads every number with leading zeros to the width of the widest one:

n=12
for i in $(seq -w 1 "$n"); do
  mkdir "week-$i"
done

That makes week-01 up to week-12. With n=120 you’d get 001 to 120, because the padding follows the largest number. A brace range like {1..$n} doesn’t work there: Bash expands braces before variables, so it stays a literal string.

When you want a fixed width or text around the number, -f takes a printf-style format. seq -f 'img_%03g.jpg' 1 3 prints img_001.jpg, img_002.jpg and img_003.jpg. A middle value is the step, so seq 0 15 45 counts in quarters of an hour, and -s ',' puts everything on one line with commas.

The caveat: seq works with floating point numbers. The manual warns that very large integers can come out approximated and that -w expects fixed point decimals for all three values. For counters in a script that’s never a problem. For long account numbers or IDs I’d use something else. Also note that -w and -f don’t mix; use the format when you need control.

Further reading: seq(1) manual page, GNU coreutils: seq invocation

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link