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?
Checking for the whole words in a file : By default, grep matches the given string/pattern even if it is found as a substring in a file. The -w option to grep makes it match only the whole words.
Let's start using grep in its most basic form. The grep command syntax is simply grep followed by any arguments, then the string we wish to search for and then finally the location in which to search.
Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With