I want to run a java command once for every match of ls | grep pattern -. In this case, I think I could do find pattern -exec java MyProg '{}' \; but I'm curious about the general case - is there an easy way to say "run a command once for every line of standard input"? (In fish or bash.)
|
|
|||
|
|
|
That's what
|
|||||||||||||||||
|
|
In Bash or any other Bourne-style shell (ash, ksh, zsh, …):
|
||||
|
|
I agree with Keith, xargs is the most general tool for the job. I usually use a 3 step approach.
There are smaller and faster ways, but this ways almost always works. A simple example:
the 2 first lines selects some files to work with, then awk prepares a nice string with a command to execute and some arguments and $1 is the first column input from the pipe. And finally I make sure that xargs sends this string to bash that just execute it. It is a little bit overkill, but this recipe has helped me in a lot of places since it is very flexible. |
|||||||
|
|
GNU Parallel is made for that kind of tasks. The simplest usage is:
Watch the intro video to learn more: http://www.youtube.com/watch?v=OpaiGYxkSuQ |
|||
|
|
|
When dealing with potentially unsanitized inputs, I like to see the entire job 'spelled out' line by line for visual inspection before I run it (especially when it's something destructive like cleaning people's mailbox's). So what I do is generate a list of parameters (ie. usernames), feed it to a file in one-record-per-line fashion, like this:
Then I open the list in
This way if your regex is incomplete, you will see in what command will have potential problems (ie. Having Once your regex is perfect and it catches all the cases you can test for/think of, then I usually convert it to a sed expression so it can be fully automated for another run. For cases where the number of lines of input prevents you from doing a visual inspection, I highly recommend echoing the command to the screen (or better yet, a log) before it executes, so if it errors out, you know exactly which command caused it to fail. Then you can go back to your original regex and adjust once more. |
||||
|
|