Interactive search and replace from shell

前端 未结 8 1868
故里飘歌
故里飘歌 2020-12-29 12:32

Search and replace over multiple files is difficult in my editor. There are plenty of tricks that can be done with find, xargs and sed

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 13:10

    A UNIX way to do this with grep, xargs, and vi/vim:

    1. Make an alias

    This will help avoiding long commands when you want to exclude certain things from grep.

    alias ge='grep --exclude=tags --exclude=TAGS --exclude-dir=.git --exclude-dir=build --exclude-dir=Build --exclude-dir=classes --exclude-dir=target--exclude-dir=Libraries --exclude=*.log --exclude=*~ --exclude=*.min.js -rOInE $*'
    
    1. Perform the search and check your file list

    Command:

    ge -l 'foo' .
    
    1. Perform the search again, telling vim to replace interactively on each file

    Command:

    ge -l 'foo' . | xargs -L 1 -o vim -c '%s/foo/bar/gc'
    

    Explanation of the command:

    • The part till the pipe is the search command repeated

    • After the pipe, we call xargs to launch vim on each file

    • "-L 1" tells xargs to launch the command on each line instead of combining all lines in a single command. If you prefer to launch vim on all files at once, remove "-L 1" from xargs.

    • "-o" tells xargs to use the actual terminal rather than /dev/null

    You have two options for this command:

    a) Launch vim on all files at once

    Advantages:

    • Command is easy to cancel: just quit vim

    Disadvantages:

    • You have to switch to each buffer in turn and re-run the "%s" command on it

    • If you have a lot of files, this can make vim consume a lot of memory (sometimes as much as a full-blown IDE!)

    b) Launch vim in turn for each file

    Advantages:

    • Everything is automated. Vim is launched and performs the search command

    • Light on memory

    Disadvantages:

    • It's hard to cancel: quitting vim will just make xargs open the next one

    I prefer variant b) as it's automated and more UNIX-like. With careful planification - inspecting the files list first, and maybe running the command on sub-directories to reduce scope - it is very nice to use.

    General advantages:

    • It can be achieved with standard UNIX tools, available on virtually every platform

    • It's nice to use

    General disadvantages:

    • You have to type the search expression twice

    • You might hit issues with bash escaping on complex search/replace expressions

提交回复
热议问题