Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do search & replace with ack in vim?

I am using the Ack plugin in Vim, which helps me to quickly search for strings in my project. However, sometimes I want to replace all or some occurrences of the found strings. You can do some kind of global search and replace using the Vim arglist like this (source) :

:args app/views/*/* :argdo %s/, :expire.*)/)/ge | update 

But instead of using args, I would prefer to do a search via Ack and then do the replace in all files that have been found. Is there a way to do it similar to the argdo command?

like image 494
Ralph von der Heyden Avatar asked Jan 25 '11 10:01

Ralph von der Heyden


People also ask

How do I start a Google search?

To get started, head over to the Google Custom Search Engine page and click the Create a custom search engine button. You'll need a Google account for this – the search engine will be saved with your Google account.

How do you do the Google search trick?

Type filetype: at the beginning of your search if you're looking for a spreadsheet, PDF, or another document. For example, if you want PDFs, write filetype:pdf in the search, along with your keyword. This tip is helpful if you're looking for other file types, too.


1 Answers

I've decided to use ack and perl to solve this problem outside of Vim so I could use the more powerful Perl regular expressions instead of the GNU subset. You could map this to a key stroke in your .vimrc.

ack -l 'pattern' | xargs perl -pi -E 's/pattern/replacement/g' 

Explanation

ack

ack is an awesome command line tool that is a mix of grep, find, and full Perl regular expressions (not just the GNU subset). It's written in pure Perl, it's fast, it has match highlighting, it works on Windows and it's friendlier to programmers than the traditional command line tools. Install it on Ubuntu with sudo apt-get install ack-grep.

xargs

xargs is an old Unix command line tool. It reads items from standard input and executes the command specified followed by the items read for standard input. So basically the list of files generated by ack are being appended to the end of the perl -pi -E 's/pattern/replacement/g' command.

perl -pi -E

Perl is a programming language.

The -p option causes Perl to create a loop around your program which iterates over filename arguments.

The -i option causes Perl to edit the file in place. You can modify this to create backups.

The -E option causes Perl to execute the one line of code specified as the program. In our case the program is just a Perl regex substitution.

For more information on Perl command line options, see perldoc perlrun. For more information on Perl, see http://www.perl.org/.

like image 163
Eric Johnson Avatar answered Sep 22 '22 11:09

Eric Johnson