6

Let's say I have a file "edit_commands" with some editing commands, like:

:1,$s/good/better/g
:1,$s/bad/worse/g

Is there a way to let vi load and run the commands in "edit_commands"?

Update: It appears the "-S" option can be used for this. Refer to: How to run a series of vim commands from command prompt

Joe Smith
  • 1,900
  • 1
  • 16
  • 15
  • 2
    FYI, there is also a dedicated [Vi and Vim Stack Exchange](https://vi.stackexchange.com/) if you don't get a good answer here. – John Kugelman Jun 26 '21 at 16:42
  • Thank you so much. Was not aware of that. – Joe Smith Jun 26 '21 at 17:08
  • 1
    Does this answer your question? [How to run a series of vim commands from command prompt](https://stackoverflow.com/questions/23235112/how-to-run-a-series-of-vim-commands-from-command-prompt) – phd Jun 26 '21 at 19:37

2 Answers2

4

It seems like you would want to use a program like sed which shares a common ancestor with vi (i.e. the 'ed' editor) for such a task:

sed -i 's/good/better/g; s/bad/worse/g' your_file

See this great sed tutorial.

Is there a reason you need to use vi to do it? You could use perl if you need more advanced regex capabilities.

mattb
  • 2,787
  • 2
  • 6
  • 20
  • This can be a workaround for some cases. However, the regex engine in sed is fairly weak (even with GNU extended). – Joe Smith Jun 26 '21 at 17:08
  • 2
    @JoeSmith You could use perl if you need advanced regex capabilities (but I don't know it well enough to give a perl based answer) – mattb Jun 26 '21 at 17:12
3

The solution in Perl may look this way:

perl -i.old -pe 's/good/better/g || s/bad/worse/g' your_file

The -i.old option saves a copy of your old file under the name your_file.old, what can be very useful when bad comes to worse and worse comes to worst...

Aditya
  • 354
  • 2
  • 6
  • 10