Reputation: 529
In vi one can replace strings globally by the following command
:%s/strtoreplace/replacedstr/g
Is it possible to put this in .bashrc (through some function may be say vireplace() ), so that one can run the same command in terminal without opening the file. Also the strings (strtoreplace,replacedstr) should be prompt inputs ($@) so that it should work for any string one wants to replace with any another any string? I want something like
function vireplace() { vim :%s/$@/$@/g $@ ;}
Upvotes: 0
Views: 434
Reputation: 20032
You can make a function calling vi
(or ed
), but when others need to understand what you have built, please use sed
.
When you are editing you can use some private tweaks that you can place in .exrc
(only on your private account).
You can add functions in $HOME/.exrc
.
nnoremap <F2> :%s/strtoreplace/replacedstr/g<Enter>
Another example for testing the script your working on:
nnoremap <F9> :w<Enter>:!%:p<Enter>
Upvotes: 1
Reputation: 44434
You can use the -c
(command) option. For example:
vireplace() { vi -c "s/$1/$2/g" -c "wq" $3; }
vireplace 1 x gash.txt
This will replace each occurrence of "1" with "x" in the file gash.txt. The -c "wq"
ensures it is not interactive - omit that if you want to use it interactively as well.
But honestly, I can't see why you want to use vim
when sed
can do the same thing simply.
Upvotes: 2