0

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  $@ ;} 
BabaYaga
  • 457
  • 5
  • 20
  • 1
    Possible duplicate of [How to run a series of vim commands from command prompt](http://stackoverflow.com/questions/23235112/how-to-run-a-series-of-vim-commands-from-command-prompt) – Andy Ray Aug 06 '16 at 04:24
  • Hi @Andy , your link is very helpful. But is there any way to put in bashrc and to use any prompt input in general? – BabaYaga Aug 06 '16 at 04:44
  • Why not use `sed` in a function? – cdarke Aug 06 '16 at 06:40
  • Hi @cdarke, yes sed will be the best option(I like bash scripting also :) ). I was just wandering if it can be done with vim. – BabaYaga Aug 06 '16 at 07:24

2 Answers2

2

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.

cdarke
  • 42,728
  • 8
  • 80
  • 84
  • Well, vim's regexes are more powerful than sed's. But then I'd just use perl. – melpomene Aug 06 '16 at 09:09
  • `sed` supports extended REs, with the `-E` option, but that's still not as powerful as Perl since 5.10. However the question specifically is a straightforward substitution. `sed` also has a much smaller footprint than `perl`. – cdarke Aug 06 '16 at 11:58
  • My `sed` accepts `-E` but doesn't document it (it only lists `-r`); weird. POSIX Extended vs. Basic RE is just a difference in syntax, not features. Perl 5.0 (1994) already had look-ahead and 5.005 (1998) added look-behind, both of which are not supported by POSIX REs. – melpomene Aug 06 '16 at 12:27
1

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>
Walter A
  • 19,067
  • 2
  • 23
  • 43