How to grep and execute a command (for every match)
grep
Solution
grep file foo | while read line ; do echo "$line" | date %s.%N ; done
More readably in a script:
grep file foo | while read line
do
echo "$line" | date %s.%N
done
For each line of input, `read` will put the value into the variable `$line`, and the `while` statement will execute the loop body between `do` and `done`. Since the value is now in a variable and not stdin, I've used `echo` to push it back into stdin, but you could just do `date %s.%N "$line"`, assuming date works that way.
Avoid using `for line in `grep file foo`` which is similar, because `for` always breaks on spaces and this becomes a nightmare for reading lists of files:
find . -iname "*blah*.dat" | while read filename; do ....
would fail with `for`.
Problem
How to grep in one file and execute for every match a command? File: ``` foo bar 42 foo bar ``` I want to execute to execute for example `date` for every match on `foo`. Following try doesn't work: ``` grep file foo | date %s.%N ``` How to do that?