1

Is it possible to add a 'prefix' to the shell glob expansion? My use case is the following, I have a program which requires repeating the option flag to pass multiple files as input:

$ ls
foo.txt bar.txt baz.txt
$ ./some-script.sh -a foo.txt -a bar.txt -a baz.txt 

I'd like to be able to use some kind of expansion to add '-a ' to each item of *txt. Is that possible? with zsh? bash?

3

You can do this in zsh using a so-called glob qualifier (see section Glob Qualifiers in the zshexpn man page):

./some-script.sh *.txt(P:-a:)

For the explanation I quote the manual:

P string The string will be prepended to each glob match as a separate word. string is delimited in the same way as arguments to the e glob qualifier described above. The qualifier can be repeated; the words are prepended separately so that the resulting command line contains the words in the same order they were given in the list of glob qualifiers.

A typical use for this is to prepend an option before all occurrences of a file name; for example, the pat‐ tern *(P:-f:) produces the command line arguments -f file1 -f file2 ...

If the modifier ^ is active, then string will be appended instead of prepended. Prepending and appending is done independently so both can be used on the same glob expression; for example by
writing *(P:foo:^P:bar:^P:baz:) which produces the command line arguments foo baz file1 bar ...

To be cautious, check first with

$ print ./some-script.sh *.txt(P:-a:)
./some-script.sh -a foo.txt -a bar.txt -a baz.txt 

if you get the desired result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.