Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

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?

like image 894
Razer Avatar asked Nov 15 '12 16:11

Razer


People also ask

How do you grep a whole word match?

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.

How do I run a grep command?

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.

How do you grep multiple lines after a match?

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!


2 Answers

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.

like image 194
Phil H Avatar answered Oct 24 '22 23:10

Phil H


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 
like image 29
Marko Kukovec Avatar answered Oct 24 '22 23:10

Marko Kukovec