Ubuntu – Search and Replace from terminal, but with confirmation

command linefindsedtext processing

In many text editors, you can do a search and replace and be given the option to inspect each found case. I'd like to be able to do something similar to this at the command line in Ubuntu. I know sed offers the ability to find and replace strings across multiple files, but is there anyway to have each replacement confirmed by the user?

Ideally, I'd like a solution that would allow me to do this "prompted" find and replace across all files within a directory.

Best Answer

How about Vim?

vim '+%s/set/bar/gc' some_file
  • + is used to run a command after the file has loaded.
  • % runs the command over the whole buffer (file).
  • gc are flags to :substitute, g for acting over all expressions in the line and c for confirming each substitution.

You can't actually prevent Vim from opening up the file, but you can automate saving and exiting:

vim '+bufdo %s/set/bar/gc | up' '+q' some_file another_file
  • bufdo runs the command over each buffer. This includes the part after |, so changes to each buffer is saved (up).
  • q quits, which exits Vim since we are now at the last buffer.