[lug] Regex from shell

Tkil tkil at scrye.com
Fri Nov 19 16:23:11 MST 2004


>>>>> "Nate" == Nate Duehr <nate at natetech.com> writes:

Nate> How'd I miss "seq" after all these years?

It's not standard POSIX, for one thing; it's a GNUism:

   $ rpm -qf /usr/bin/seq
   coreutils-5.2.1-7

Although it's easy enough to emulate in in Perl or any other language
of your choice:

   http://scrye.com/~tkil/perl/seq

(Note that my version uses "-w" in a different way than the gnu 'seq'
does...)

My most common use for it lately is hammering web sites:

   for i in $( seq -w 1 20 )
   do
      wget http://your.big.server.here/files/part$i.bin
   done

I guess I was reminded of "what's your favorite obscure CLI utility?"
by Kevin's recent post to his tummy blog:

   http://www.tummy.com/journals/entries/kevin_20041119_134526

While 'seq' is getting more common, there is another tool I use
occasionally: "pmv".  It's my own implementation of a perl-based
"rename by regex" utility; there is one (called "rename", amazingly
enough) in the perl distribution, but I didn't know that at the time.

Mine allows arbitrary perl expressions as the destination filename, so
you can do calculations, convert upper/lower case, use 'sprintf',
Perl's magic increment, etc.

As an example, say we have files like so:

   part1 part2 ... part9 part10 ... part99 part100

And we want to normalize all those numbers to be three digits, maybe
padded by zeros.  You can play some games with ksh/bash parameter
substitution patterns to accomplish this, but pmv lets me do stuff
like this:

   pmv '^part(\d+)$' 'sprintf "part%03d", $1'

   # bash version:
   for i in $( seq -w 1 99 )
   do
      n=${i#0}
      mv part$n part0$i
   done

Two other examples from the meagre documentation:

   pmv '(.*)\.foo' '"$1.bar"'

   # bash version:
   for i in *.foo
   do
      n=${i%.foo}.bar
      mv $i $n
   done

And

   # change spaces to underscore
   pmv ' ' '$_ = $file; s/\s/_/g; $_'

   # no easy bash equiv that comes to mind...

Not at all a finished product, but I've found it useful.  Feel free to
play with it:

   http://scrye.com/~tkil/perl/pmv

Geekily,
t.



More information about the LUG mailing list