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
Vi edit modesTo enter Insert mode, press i . In Insert mode, you can enter text, use the Enter key to go to a new line, use the arrow keys to navigate text, and use vi as a free-form text editor. To return to Command mode, press the Esc key once. [ Looking for a different text editor?
From Command Mode :w Write changes to your file. :sh Return to the shell to enter a number of commands without leaving vi. Press <Control>d to return to vi editing.
Command Mode: When vi starts up, it is in Command Mode. This mode is where vi interprets any characters we type as commands and thus does not display them in the window. This mode allows us to move through a file, and to delete, copy, or paste a piece of text.
The vi has the capability to run commands from within the editor. To run a command, you only need to go to the command mode and type :! command.
How to run Linux Commands within vi/vim editor 1 Insert Linux/Unix Command Output in vi editor : Example: Insert the output of hostname in /etc/hosts file. ... 2 Starting a shell within vi Editor. Type of a shell that is started is determined by the $SHELL variable. ... 3 Open an existing file within the vi editor. ...
Saving and Quitting. You can save and quit vi from command mode. First, ensure you’re in command mode by pressing the escape key (pressing the escape key again does nothing if you’re already in command mode.) Type :wq and press enter to write the file to disk and quit vi.
Start typing and Vi will insert the characters you type into the file rather than trying to interpret them as commands. Once you’re done in insert mode, press the escape key to return to command mode. You can save and quit vi from command mode.
Vi is a modal text editor, and it opens in command mode. Trying to type at this screen will result in unexpected behavior. While in command mode, you can move the cursor around with the arrow keys.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With