0

I have multiple files with a string like:

source /PATH/TO/OLD/ENV.sh

And this needs to be replaced with:

source /PATH/TO/NEW/ENV1.sh
source /PATH/TO/NEW/ENV2.sh

Usually, I use sed to replace strings. What's the 'vim-way' of doing this?
Thanks.

nac001
  • 147
  • 1
  • 8
  • Vim's :substitute command is incredibly similar to sed's. See :h :s. For multiple files, see :h :argdo and :h bufdo – Rich Jul 09 '18 at 13:45

1 Answers1

2

You can use \r to represent a newline in :substitute patterns:

:%s,source /PATH/TO/OLD/ENV.sh,source /PATH/TO/NEW/ENV1.sh\rsource /PATH/TO/NEW/ENV2.sh/,

Note that in substitute patterns \n means NULL byte, not newline. This is inconsistent and confusing (I'm not sure what the reason for it is, it's a vi quirk you'll just have to remember)

I used , instead of / to avoid having to escape all the /s in the path; see What does it mean to replace slashes (/) by exclamation marks (!) in a substitute command?

You can use the :bufdo, :windo, and :tabdo commands to run any command on multiple buffers, windows, or tabs. For example:

:bufdo :%s,source /PATH/TO/OLD/ENV.sh,source /PATH/TO/NEW/ENV1.sh\rsource /PATH/TO/NEW/ENV2.sh,
:wa

Which should do what you want.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271