OB7DEV
OB7DEV

Reputation: 143

execute command on files returned by grep

Say I want to edit every .html file in a directory one after the other using vim, I can do this with: find . -name "*.html" -exec vim {} \;

But what if I only want to edit every html file containing a certain string one after the other? I use grep to find files containing those strings, but how can I pipe each one to vim similar to the find command. Perphaps I should use something other than grep, or somehow pipe the find command to grep and then exec vim. Does anyone know how to edit files containing a certain string one after the other, in the same fashion the find command example I give above would?

Upvotes: 2

Views: 4147

Answers (3)

Angel Asenov
Angel Asenov

Reputation: 64

Solution with a for cycle:

for i in $(find . -type f -name '*.html'); do vim $i; done

This should open all files in a separate vim session once you close the previous.

Upvotes: 0

SLePort
SLePort

Reputation: 15461

With find :

find . -type f -name '*.html' -exec bash -c 'grep -q "yourtext" "${1}" && vim "${1}"' _ {} \;

On each files, calls bash commands that grep the file with yourtext and open it with vim if text is matching.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753970

grep -l 'certain string' *.html | xargs vim

This assumes you don't have eccentric file names with spaces etc in them. If you have to deal with eccentric file names, check whether your grep has a -z option to terminate output lines with null bytes (and xargs has a -0 option to read such inputs), and if so, then:

grep -zl 'certain string' *.html | xargs -0 vim

If you need to search subdirectories, maybe your version of Bash has support for **:

grep -zl 'certain string' **/*.html | xargs -0 vim

Note: these commands run vim on batches of files. If you must run it once per file, then you need to use -n 1 as extra options to xargs before you mention vim. If you have GNU xargs, you can use -r to prevent it running vim when there are no file names in its input (none of the files scanned by grep contain the 'certain string').

The variations can be continued as you invent new ways to confuse things.

Upvotes: 8

Related Questions