2

I have a list arguments needed to be passed one by one to another command, since the command only accepts one argument at time, any shell pipe I can use? Thank you in advance.

For example,

$ ls -al | awk '{print $9}'

the command will return a list of folder names, then I need send these names as arguement to anther command, which only accepts on command per execution.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
perigee
  • 9,438
  • 11
  • 31
  • 35

2 Answers2

6

I don't understand the ls -al | awk ... analogy. What is the point of including this code example?

If you have a whitespace delimited list of arguments, using a utility command like xargs will supply each argument to a command one-by-one by default. You can change this default behavior, but it doesn't seem like that you'd need to. You can use xargs as follows...

ls -al | awk '{print $9}' | xargs cat

...to cat the contents of each file output by the ls -al command. Does this help?

It should be noted though that ls is a porcelain command and not a plumbing command. In other words, it is best practice to not rely on the output of ls for a command pipeline. A utility like find, however, is a plumbing command and is preferable to use as a part of a pipeline.

wpcarro
  • 1,528
  • 10
  • 13
  • 3
    You may want/need to add `-L 1` to your `xargs` command depending on the output format of whatever your first command is. – Matthew Burke Sep 19 '16 at 17:19
  • 1
    Of course, `cat .[!.]* *` works much better. In particular, the Awk will munge any filename which contains whitespace, which the plain wildcard expansion will not. – tripleee Sep 19 '16 at 17:58
  • 1
    with `xargs -L 1 cat`, give me the right output, as the list is line separated. Thx a lot – perigee Sep 19 '16 at 19:36
  • Interesting, I've never heard of "porcelain" and "plumbing" commands before. But at least found some info on the net. :) – Matthias W. Sep 19 '16 at 21:38
1

I suggest to use find:

find . -mindepth 1 -maxdepth 1 -type d -exec your_command {} \;

This will call your_command for any folder in the current directory expect of . and ..

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    This selects only directories, which seems to be anathema to what the OP asked for. – tripleee Sep 19 '16 at 17:58
  • No, it just seems to be anathema to OP's unfinished command. He states: `... the command will return a list of folder names`. That makes me think that `your_command` will likely just accept folders. – hek2mgl Sep 19 '16 at 18:11