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.

1
  • Vim's :substitute command is incredibly similar to sed's. See :h :s. For multiple files, see :h :argdo and :h bufdo
    – Rich
    Commented Jul 9, 2018 at 13:45

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.