Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: more fun with parameter expansion

On Jun 16,  2:53pm, Clint Adams wrote:
> Subject: more fun with parameter expansion
> This is for someone who wants to take a directory tree and convert all
> the filenames (and directory names) to lowercase, replacing spaces
> with underscores.  It presumes that you are using GNU mv and have
> MARK_DIRS set.  I'm sure that someone can make it more efficient.

I dunno about efficient, but you can do it with only one glob and one
loop, and it doesn't need to care about MARK_DIRS.

Oh, and your solution missed file names that began with a dot, unless you
meant to say that both MARK_DIRS and GLOB_DOTS were needed ...

for f in **/*(DNon); do
  mv -v $f ${${(M)f%/*}:+${${f%/*}:l:gs/ /_/}}${${${(M)f%/*}:-$f}:l:gs/ /_/}

The `(on)' (order by name) is probably unnecessary, and won't work in 3.0.x
(though everything else should).

Writing that one-liner out a bit longer might make this more readable:

  t=${(M)f%/*}     # The tail of the path, including leading slash
  h=${t:+${f%/*}}  # The head of the path if the tail is non-empty
  t=${t:-$f}       # The tail is the path when the tail is empty

  h=$h:l           # Downcase the head, same as ${(L)h}
  t=$t:l           # Downcase the tail

  h=$h:gs/ /_/
  t=$h:gs/ /_/

  mv $f $h$t

The last five steps could be written as

  mv $f ${${:-$h$t}:l:gs/ /_/}

Do you see what that's doing?  Exercise: Rewrite the "mv" in my for-loop
with that trick, to make it at least 8 characters shorter.

Incidentally, you can turn on MARK_DIRS for individual globs like this:

	echo *(M)

Messages sorted by: Reverse Date, Date, Thread, Author