9

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?

gregseth
  • 747

2 Answers2

12

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.

mpy
  • 28,816
2

I am expending @mpy answer for zsh in the case we do not want any spaces between the prefix and the filename, or if we also want a suffix,or any other string manipulation:

print -l *.txt(e:'REPLY=PFX_${REPLY}_SFX':)

which gives:

PFX_foo.txt_SFX
PFX_bar.txt_SFX
PFX_baz.txt_SFX

Note that the single quotes are important to avoid $REPLY being expanded prematurely.

For instance (even if dd will only process the last if= argument):

dd *.img(e:'REPLY=if=$REPLY':)

http://zsh.sourceforge.net/Doc/Release/Expansion.html#index-reply_002c-use-of

calandoa
  • 219