How to grep and execute a command (for every match)

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.


What you really need is a xargs command. http://en.wikipedia.org/wiki/Xargs

grep file foo | xargs date %s.%N

example of matching some files and converting matches to the full windows path in Cygwin environment

$ find $(pwd) -type f -exec ls -1 {} \; | grep '\(_en\|_es\|_zh\)\.\(path\)$' | xargs cygpath -w

Tags:

Grep