grep for string and open matching files in text editor

26 views Asked by At

I wasn't able to find an answer for this simple question. I had a solution for it years ago and I think it involved something like { }, but I've totally forgotten now.

I'm looking to grep for a pattern in all files in a directory and open them in a text editor. I tend to use nedit and subl.

grep -il "gating" *

will find matching files, but I can't seem to send those matching filenames as arguments to open an editor.

grep -il "gating" * | xargs subl

either complains that the program doesn't exist or it opens up some random stuff.

subl file1 file2 file3

will open all 3 files in the same editor window. Doing this with grep would be ideal. I thought maybe piping it would work, but grasp of shell commands is limited, at best.

1

There are 1 answers

0
jhnc On

With utilities that have nonstandard null options, you could try something like:

grep -Zil "gating" * | xargs -0 subl

However, if the command run by xargs needs input from a terminal, something more complicated may be needed.

A more general approach could be to use find instead of xargs:

find * -exec grep -qi "gating" {} \; -exec subl {} +

This runs grep on each file in turn (I assume * doesn't select directories), and if it finds a match, the filename is appended to the subl command. There is no pipeline, so stdin for the final command remains the terminal.

subl will be invoked with batches of files (as many each time as will fit in the maximum allowed length of a command - Cf. xargs's -s option).