SED ask for confirmation before each replace

SED ask for confirmation before each replace

Times when you are trying to find and replace strings from multiple files or a single file from command line we use sed.

The following is the syntax we generally use.

sed -i ‘s/PATTERN/NEWPATTERN/g’ FILE_NAME

However, sed just finds and replaces the string from the file. It never asks for confirmation. So the possibility of verifying the change is never possible. We have to manually verify the changes made by sed later.

We might come across some files or part of file where the string replacement isn’t required.

sed, however doesn’t provide a confirmation option. I am providing an alternative here.

SED ask for confirmation before each replace

I agree that the title is misleading! But this intend here is to provide an alternative solution where you can find and replace the regex you want from multiple files.

A more better option is using vim from command line.

The following is the syntax.

vim -c ‘%s/PATTERN/NEWPATTERN/gc’ -c ‘wq’ FILE_NAME

So you can combine this option with the for loop or xargs and use it to replace the regex from the different files.

I am providing the example of a for loop here.

for FILES in file1.txt file2.txt file3.txt;
do
vim -c ‘%s/PATTERN/NEWPATTERN/gc’ -c ‘wq’ $FILES
done

This should save a lot of time for you!

SED ask for confirmation before each replace

3 Comments

  • Liloulinx

    August 25, 2015 at 2:24 pm Reply

    I found that the solution using vim is a good alternative for sed with confirmation.
    However I need to use it in a generic mode. I need to use it in a script for which we give PATTERN and REPLACEMENT as arguments. So they must be varibales.
    So, I have used:

    vim -c '%s/$1/$2/gc' -c 'wq' file.in

    but it doesn’t work. The script try to replace the string “$1” and not the variable $1.
    Do you have a solution for this ?
    Thanks in advance.

    • Anonnymous

      October 6, 2015 at 7:53 am Reply

      Well, I have a similar function but i use :

      “`
      vim -c ‘%s/’$1’/’$2’/gc’ -c ‘wq’
      “`

      • Gagan

        October 12, 2015 at 4:57 pm Reply

        Yea, that one works! Just get rid of ‘c’ so that it doesn’t ask for confirmation every time.

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.