Basic example using grep (note that grep would not be my only use-case for this):
$ grep -Irl "foo"
path/to/directory/help.js
path/to/directory/config.js
path/to/directory/task.js
Now I want to open the config.js
file in Vi. My normal method would be:
$ vi path/to/directory/config.js
which I had to either type by hand with the assistance of tab-completion, or I highlighted the filename from the grep result and copy/pasted it.
But I'd like to be able to Vi the file by just specifying that it was the 2nd result in the grep command. So something like:
$ grep -Irl "foo" | xargs vi 2
Obviously xargs would not work like that, was just an example. But I'm trying to find if there's a way using xargs (or any other utility) to accomplish this and I'm not finding it.
Something that a teammate suggested to me was to use head
and tail
together, like this:
$ grep -Irl "foo" | tail -n 1 | xargs vi
would retrieve task.js, and
$ grep -Irl "foo" | head -n 2 | tail -n 1 | xargs vi
would retrieve config.js. Wondering if there is a less verbose method.
How about
vi $( grep -IrL "foo" | awk "NR==3" )
This uses AWK to find the appropriate line. The output is then used as a command line argument for vi.
I'm oldschool, so I prefer the equivalent, but slightly frowned upon version-
vi ` grep -IrL "foo" | awk "NR==3" `
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments