Generate Arguments List for mkdir -p Using Zsh Parameter Expansion

zsh

I have something like this:

% ls -1dF /tmp/foo/*
/tmp/foo/000f9e956feab3ee4625aebb65ae7bae9533cdbc/
/tmp/foo/002e34c2218f2c86fefd2876f0e5c2559c5fb3c4/
/tmp/foo/00b483576791bab751e6cb7ee0a7143af43a8069/
.
.
.
/tmp/foo/fedd0f7b545e7ae9600142656756456bc16874d3/
/tmp/foo/ff51ac87609012137cfcb02f36624f81cdc10788/
/tmp/foo/ff8b983a7411395344cad64182cb17e7cdefa55e/

I want to create a directory bar under each of the subdirectories under foo.

If I try to do this with

% mkdir -p /tmp/foo/*/bar

…I get the error

zsh: no matches found: /tmp/foo/*/bar

(In hindsight, I can understand the reason for the error.)

I know that I can solve the original problem with a for-loop, but I'm curious to know if zsh supports some form of parameter expansion that would produce the desired argument for a single invocation of mkdir -p. IOW, a parameter expansion equivalent to "append /bar to every prefix generated by expanding /tmp/foo/*", resulting in

% mkdir -p /tmp/foo/000f9e956feab3ee4625aebb65ae7bae9533cdbc/bar ... /tmp/foo/ff8b983a7411395344cad64182cb17e7cdefa55e/bar

Best Answer

setopt histsubstpattern extendedglob
mkdir -p /tmp/foo/*(#q/:s_%_/bar_)

This is extended globbing that has a quiet glob flag that uses a glob qualifier to match only directories and a modifier to perform a substitution (using the % pattern character that is only available in history substitution pattern mode) that appends a string to each word.

man zshexpn
Related Question