Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

egrep results to vim as a line referenced filelist

Tags:

grep

bash

shell

vim

In a shell I use the following function to create a filelist and pass it to vim.

Feels alright, but I lost the line reference, I open the files in correct order but then I have to search again for the text as the cursor starts at first line.

Actual function on ~/.bashrc

function vimgrep(){
   vim `grep -IR "$1" * | awk -F: '$1!=f{print ""$1"";f=$1}' | grep -v 'Test\|test'` +ls
}

function vimgrep2(){
   vim `grep -IR "$1" * | awk -F: '$1!=f{print ""$1"";f=$1}' ` +ls
}

Obs.: filelist must come from shell to vim, and then it must keep the line reference of the buffered files, just like with the results of :make when it catches any error (but without the bottom window [:cwindow]).

edited: Ok... not so elegant, but I could pass the searched string to vim as +/"$1", like:

   vim `grep -IR "$1" * | awk -F: '$1!=f{print ""$1"";f=$1}' ` +/"$1"

Would be better if the script doesn't use a temporary file.

like image 415
Rodrigo Gurgel Avatar asked Jul 27 '12 17:07

Rodrigo Gurgel


2 Answers

Vim also comes with a vimgrep command you could use

function vimgrep() {
    local regex="$1"

    if [[ -z "$regex" ]]; then
        echo "Usage: $0 regex" 1>&2
        exit 1
    fi

    vim -c "vimgrep /$regex/ **"
}

Be careful of running it in a directory with a lot of files below it.

like image 114
Swiss Avatar answered Sep 20 '22 22:09

Swiss


Using Line Numbers with an External Grep

To the best of my knowledge, it is not possible to open more than one file at a time using the line number option flag because Vim will only apply the flag to the first file in the list. The man page says:

 +[num]      For the first file the cursor will be positioned on line  
             "num". If "num" is missing, the cursor will be positioned
             on the last line.

So, you could call the function on each file one at a time, or put the function call in a loop that operates on two positional parameters (a file name and a regular expression) at a time. The former is certainly easier. For example:

vimgrep () {
    local file="$1"
    shift || return 1
    vim +$(egrep -n "$1" "$file" | cut -d: -f1) "$file"
}

# Sample function call.
vimgrep /etc/password '^www-data'
like image 32
Todd A. Jacobs Avatar answered Sep 20 '22 22:09

Todd A. Jacobs