1

I am using a command that takes input of the form

command [-a input_files]*

So I can call command -a foo or command -a foo -a bar -a baz.

Now, I am trying to automate a workflow and would like to pass all files in a directory to the command. Is there a way to get a wildcard to do this? I know about * but this doesn't allow me to insert the mandatory -a prefix: command * would just execute command foo bar baz.

Is such an operation possibly natively in bash, or will I need to use sed, etc.?

  • Which command do you have in mind? Depending on the command, different handling may be required. – George Vasiliou Jul 5 '17 at 20:34
  • I'm using lcov, an instrumentation program. – baum Jul 5 '17 at 20:36
  • I have come up with for f in *; do echo -n "-a $f "; done, the result of which can be store in a variable and passed to the program. Better solutions would be appreciated. – baum Jul 5 '17 at 20:37
  • 2
    In ZSH, this is done with command *(P:-a:) – thrig Jul 5 '17 at 20:45
  • xargs could be a solution but i don't have lcov or a program with lcov behavior to test it.... – George Vasiliou Jul 5 '17 at 20:54
2

Probably the shortest way is to use printf:

lcov $(printf -- ' -a %s' *)

But it still might fail for some programs, please test and report back.

| improve this answer | |
  • What are you thinking it might fail on? Strange filenames in the directory? I'm not particularly worried about this in my case because I am operating on a well-formatted and static directory, but would be interested to hear your thoughts on the general case. It works perfectly fine, for example, for filenames with spaces. – baum Jul 6 '17 at 14:44
  • 1
    @baum It may fail for files with double (or more) spaces (or tabs), not only one, as the command execution is not quoted (affected by IFS splitting by the shell). And it probably will fail for files with newlines (a very infrequent issue). No problems with multi byte names (utf8). – Isaac Jul 6 '17 at 18:22
0

Build up an array args that has -a ahead of every (*) file, then run command with the whole list:

for f in *
do
  args+=(-a "$f")
done
command "${args[@]}"
| improve this answer | |
  • That will include directories (if they exist). And, maybe hint at the solution for a path with spaces (the question) using for f in "$SOURCE"/*. – Isaac Jul 6 '17 at 4:44

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.