Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interactive search and replace from shell

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/awk incluing search-and replace in multiple files. But somehow I couldn't find a way to make this interactive. Do you know a way to do that?

like image 900
Łukasz Lew Avatar asked Jun 28 '11 07:06

Łukasz Lew


People also ask

How do I find and replace in shell?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do I find and replace in bash?

To replace content in a file, you must search for the particular file string. The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.

What is interactive mode in shell?

An interactive shell is defined as the shell that simply takes commands as input on tty from the user and acknowledges the output to the user. This shell also reads startup files that occurred during activation and displays a prompt. It also enables job control by default.

How do I change all occurrences of a string in Unix?

unix is a powerful. Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.


1 Answers

From jhvaras answer, I've made this bash command to quickly search and replace (to add to .bashrc):

replace () {
    if [ $# -lt 2 ]
    then
        echo "Recursive, interactive text replacement"
        echo "Usage: replace text replacement"
        return
    fi

    vim -u NONE -c ":execute ':argdo %s/$1/$2/gc | update' | :q" $(ag $1 -l)
}

It's used as follows:

~$ replace some_text some_new_text

It uses ag to search in advance, as it's probably faster than letting vim do the work, but you can probably substitute anything else you like. It also calls vim with no plugins for maximum speed, and after it has finished all substitutions it automatically quits and goes back to the shell.

like image 199
Svalorzen Avatar answered Sep 17 '22 14:09

Svalorzen