0

Say I'm doing a grep for something and in the results I have a bunch of files? How can I quickly open one of those files in vim without using the mouse and without or typing the name by hand?

For example, with my mouse I can CMD-Click the name of the file and it opens in vim. But I would like to have the same speed without using the mouse.

UPDATE: grep is just one example, I would like to know if there's a universal way to would work for any command. Something like a bash variable that holds the last file name or whatever. And also, it should open just the one file that I want.

Thanks.

2 Answers 2

1

When you use grep -l, file names won't be repeated, so you don't need sort | uniq or sort -u.

You can also use -p to open all files in tabs.

grep -rlH "mail" . | xargs vim -p
4
  • That won't open a specific file, it will open all of them. I want to target just one of them... and it would ideally work for any command, not just grep.
    – Cezar
    May 25, 2017 at 13:09
  • @Cezar - the only way to specify which file is to use head -n 1 for the first line or tail -n 1 for the last line. There's no way for bash to know which file you want without more specificity in the commands sent to it.
    – Cometsong
    Jul 14, 2017 at 17:02
  • @Cometsong I'm wondering what is the best way to navigate a project tree from the terminal. Where you have a bunch of files that have the same names and such.
    – Cezar
    Jul 17, 2017 at 12:57
  • @Cezar - there are options for this: 1) denote the file or the number of the file prior to the cmd running at all; 2) go through every one sequentially, opening each in a vim instance; 3) generate a list at the end of the command (prob easiest using a bash wrapper function) to ask you which one of the resulting files you'd like to open in vim. There is a ton of variability in this type of task - how many files are being queried? how many are in the resulting set? how big is the project?
    – Cometsong
    Jul 17, 2017 at 18:27
0

You can make grep print just the file names with grep -l -H. You could then pipe this to sort and uniq to get a list of files. This could then be passed to vim with xargs.

Lets say you wanted to open all files in the current directory or sub directories that contain the word mail, you would type something like this:

grep -r -l -H "mail" . | sort | uniq | xargs vim
2
  • sort -u is the same as sort | uniq with less typing. You should also be able to use grep -rlH mail ;-) May 24, 2017 at 12:40
  • That won't open a specific file, it will open all of them. I want to target just one of them... and it would ideally work for any command, not just grep.
    – Cezar
    May 25, 2017 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.