6

I often use grep with the -n option to list line numbers, e.g.

$ grep -n xyz .*
/ext1/acheong/foo/bar/a.cc:42:    inline bool abc(int xyz);
/ext1/acheong/foo/bar/a.cc:43:    inline bool def(int xyz);
/ext1/acheong/foo/bar/b.cc:415:            int xyz = result;
/ext1/acheong/foo/bar/b.cc:490:                xyz += result;
$

Would it be possible to alias vim in such a way that doing

vim /ext1/acheong/foo/bar/b.cc:415

would open the file and seek line 415 automatically?

Is it possible in csh? (Yes, yes, csh brings out the devil and all that is unholy; but I've no choice...) An answer for other shells would be useful, too.

6 Answers6

9

Well, it's not an alias, you can use vim like this:

vim +<LineNumberHere> fileName

So, for example

vim +150 .bash_history

opens your .bash_history file (for bash), and navigates to line 150.

Incidentally, you can also do this with search terms. For example

vim +/MyTerm MyFile

opens MyFile and navigates to the first occurrence of MyTerm from the top.

Enjoy!

5

One solution to this is to use the file_line.vim plugin, which lets you specify a file name and line number as an argument to Vim or on Vim's command line, just as you've shown.

Another is this script,

$ cat $(which vimgrep)
#!/bin/bash

tmp=$(mktemp)

cat > $tmp
exec < /dev/tty
vim --cmd 'let &efm=&gfm' -q $tmp "$@"
rm $tmp

which can be used like this:

$ grep -Hn xyz .* | vimgrep

and which loads all the matches into Vim's quickfix error list. See

:help quickfix.txt

Note the -H option to grep to ensure that the file name is included in grep's output even if .* expands to only one file name.

garyjohn
  • 36,494
1

vim-fetch is able to open files at a specific location provided as colon separated values.

1

The simplest and resilient way:

  1. Create a new file ~/.bin/vim and paste the code below
  2. Create shell alias: in ~/.bashrc add line alias vi=~/.bin/vim

This is called parameter substitution and will basically split the provided parameters by ':' (colon).

#!/usr/bin/env bash

if [[ ${1} == *":"* ]]; then
    vim ${1/:*/} -c "${1/*:/}"
else
    vim ${1}
fi

Then you could simply use it as: vim /ext1/acheong/foo/bar/b.cc:415

ww12
  • 111
1

You could do your grepping from Vim itself:

:grep xyz *

then open the quickfix window:

:cw
romainl
  • 23,415
0

You can open it in BBEdit as long you have BBEdit define in .bashrc

$ grep EDITOR ~/.bashrc
export EDITOR="bbedit -w"
$ bbedit .bash_history:17:55
bbedit [Filepath/filename]:[line number]:[column number]