Vim Substitution - vim

I always wanted to know, how you can substitute within given parameters.
If you have a line like this:
123,Hello,World,(I am, here), unknown
and you wnat to replace World with Foobar then this is an easy task: :%s/World/Foobar/
Now I wonder how I can get rid of a , which is wihtin the ( ).
Theoretically I just have to find the first occurance of ( then substitute the , with a blank until ).

Try lookahead and lookbehind assertions:
%s/([^)]*\zs,\ze.*)//
(\zs and \ze tell where pattern starts and end)
or
%s/\(([^)]*\)\#<=,\(.*)\)\#=//
The first one is more readable, the second one uses \( ... \) groupings with parentheses inside groups which makes it look like obfuscated, and \#<= which apart from being a nice ASCII-art duck is the lookbehind operator, and \#= that is the lookahead operator.
References: :help pattern (more detail at :help /\#=, :help /\ze, etc.)
You use the GUI and want to try those commands? Copy them into the clipboard and run :#+ inside Gvim.

Modifying slightly the answer of #Tom can give you a quite good and "a bit" more readable result :
%s/\(.*\)(\(.*\),\(.*\))\(.*\)/\1(\2\3)\4/
That way you will have : in \1 will store what is at the left outside of the parenthesis, \4 what is at the right outside of the parenthesis and \2 and \3 what is inside the parenthesis, respectively on the left (\2) and on the right (\3).
With that you can easily swap your elements if your file is organised as column.

You can also select the text you want to change (either with visual or visual-block modes) and enter the : to start the replace command. vi will automatically start the command with :'<,'> which applies the command to the selected area.
Replacing a , can be done with:
:'<,'>s/,/ /g

For your example, this is the same thing as suggested by #ubuntuguy
%s/\(.*\)(\(.*\),\(.*\)/\1(\2\3
This will do the exact replacement you want.

Yet another approach, based on the fact that actually you want to substitute only the first occurrence of , inside the parenthesis:
:%s#\((.\{-}\),#\1 #
Explanation:
:%s for substitution in the whole file (don't use % if you want to work only with the current line)
we can use # or : as a delimiter to make the command more readable
in (.\{-} we ask to find any symbol (dot) after the left parenthesis and the rest stands for 0 or more occurrence (as few as possible) of this symbol. This expression is put inside \(...\) to be able to refer to this group as \1 in the future.

Related

Various ways of substitution in Vim

How would you do to turn this
Dragon.Ball.026.C'est.la.finale.!!.Kame.hame.ha.mkv
Dragon.Ball.027.Goku...Le.moment.le.plus.critique.mkv
Dragon.Ball.028.Impact.!!.La.puissance.contre.la.puissance.mkv
Dragon.Ball.029.A.nouveau,.l'aventure..Le.lac.errant.mkv
Dragon.Ball.030.Pilaf.et.l'armée.mystérieuse.mkv
into this
Dragon.Ball.026.mkv
Dragon.Ball.027.mkv
Dragon.Ball.028.mkv
Dragon.Ball.029.mkv
Dragon.Ball.030.mkv
I succeeded with difficulty with a macro, but there may be a simple way ?
(substitution, block mode, macro or anything else..)
It's for my personal knowledge,
Regards.
A slightly shorter solution
:%s/\d\.\zs.*\.//
That is, find digit followed by dot; then match and delete everything until (and including) the last dot. The regex is guaranteed to work right as the "star" operator is greedy.
You can remember parts of a match with capture groups: \( and \). So match and
remember everything up to the last digit \d, plus the rest of the line .*
(but don't remember this part), and use \1 to put back the remembered part of
the line, and manually add the extension .mkv:
:%s/\(.*\d\).*/\1.mkv
See :help pattern-searches, :help pattern-atoms and in particular :help \(
Note
You could also remember the extension with a second capture group and add it
back like with \2:
:%s/\(.*\d\).*\(\.mkv\)/\1\2

vim multiple character substitute regex issue

I am little new to Vim world. I am trying to substitute *=, ~=(actually [special char]=) in to [whatever is symbol]=(adding space both sides). Here is my substitute command:
:%s/[~,\*]=/ = /g
the problem in this case is that I am not able to add respective special symbol before the equal sign. Can you help me...
This is a classic capture and replace use case. Capture the symbol part by enclosing it in \(...\), and then reference it in the replacement part via \1. You'll find more details at :help s/\1 (or :help :substitute in general):
:%s/\([~,\*]\)=/ \1= /g
Alternatively, you can start the match only on the = with \zs. This asserts that the symbol part is there, but as it isn't included in the match, you don't need to reference it:
:%s/[~,\*]\zs=/ = /g
The same trick can be applied with \ze at the end. As you can see, this often results in shorter commands.
This is probably the simplest answer to your question:
:%s/[~,\*]=/ & /
An& in the replace segment means 'entire match'.

How to efficiently switch arguments in vim

I come upon one scenario when editing a file in vim and I still haven't found a way to do it quickly in vim way. When editing a call of a function, I offently put my arguments in a wrong order.
anyFunction(arg2, arg1)
When arriving on this situation, I have to find arg2 / delete it / append it before the ')' / deal with the ', ' / etc.
Isn't it a better way to this task quickly ? I am open to any idea (macro/ shortcut / plugin) even if I'd rather have a 'vim only' way of doing this
You need two things:
A text object to quickly select an argument (as they aren't always that simple like in your example). argtextobj plugin (my improved fork here) does this.
Though you can use delete + visual mode + paste + go back + paste, a plugin to swap text makes this much easier. My SwapText plugin or the already mentioned exchange plugin both do that job.
put this mapping in your _vimrc.
" gw : Swap word with next word
nmap <silent> gw :s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l>
then in normal mode with the cursor anywhere in arg1 type gw to swap parameters
anyFunction(arg1, arg2)
Explanation:-
arg1 the separator (here a comma) and arg2 are put into regexp memories 1 2 3
the substitute reverses them to 3 2 1
Control-O return to last position
Control-L redraw the screen
Note that the separator is any non-alphanumeric character or string e,g whitespace
I actually made a plugin to deal with a exact situation called argumentative.vim. (Sorry for the plug.)
Argumentative.vim provides the following mappings:
[, and ], motions which will go to the previous or next argument
<, and >, to shift an argument left or right
i, and a, argument text objects. e.g. da,, ci, or yi,
So with this plugin you move to the argument in question and then do a <, or >, as many times as needed. It can also take a count e.g. 2>,.
If you have Tim Pope's excellent repeat.vim plugin installed <, and >, become repeatable with the . command.
I would recommend a plugin: vim-exchange for that:
https://github.com/tommcdo/vim-exchange
This is a perfect use for a regular expression search and replace.
You want to find "anyFunction(", then swap anything up to the ',' with anything from the ',' to the ')'. This is fairly straightforward, using [^,]* for "anything up to the ','" and [^)]* for "anything up to the ')'". Use \(...\) to capture each thing, and \1, \2 to refer to those things in the replacement:
:s#anyFunction(\s*\([^,]*\),\s*\([^)]*\)#anyFunction(\2, \1#g
Note how I use \s* to allow any whitespace between the "anyFunction(" and the first thing, and also between the ',' and the second thing.
If you want this to be able to span multiple lines, you can use \_s instead of \s, and capture the whitespace if you want to maintain the multi-line format:
:s#anyFunction(\(\_s*\)\([^,]*\),\(\_s*\)\([^)]*\)#anyFunction(\1\4,\3\2#g
There is also a multi-line variant of [...] collections, for example \_[^,] meaning "anything (even a new line) except for a ',' " which you could use in the pattern if your use case demands it.
For details, consult the help topics for: /\s, /\_s, /\1, /\(, and /[.
If you want a more general-purpose mapping to use at every location, you can use the cursor position in your regular expression, rather than keying off the function name. The cursor position in a regular expression is matched using \%# as demonstrated here: http://vim.wikia.com/wiki/Exchanging_adjacent_words
Similar to what Peter Rincker suggested (Argumentative), sideways also does what you describe.

Substitute `number` with `(number)` in multiple lines

I am a beginner at Vim and I've been reading about substitution but I haven't found an answer to this question.
Let's say I have some numbers in a file like so:
1
2
3
And I want to get:
(1)
(2)
(3)
I think the command should resemble something like :s:\d\+:........ Also, what's the difference between :s/foo/bar and :s:foo:bar ?
Thanks
Here is an alternative, slightly less verbose, solution:
:%s/^\d\+/(&)
Explanation:
^ anchors the pattern to the beginning of the line
\d is the atom that covers 0123456789
\+ matches one or more of the preceding item
& is a shorthand for \0, the whole match
Let me address those in reverse.
First: there's no difference between :s/foo/bar and :s:foo:bar; whatever delimiter you use after the s, vim will expect you to use from then on. This can be nice if you have a substitution involving lots of slashes, for instance.
For the first: to do this to the first number on the current line (assuming no commas, decimal places, etc), you could do
:s:\(\d\+\):(\1)
The \(...\) doesn't change what is matched - rather, it tells vim to remember whatever matched what is inside, and store it. The first \(...\) is stored in \1, the second in \2, etc. So, when you do the replacement, you can reference \1 to get the number back.
If you want to change ALL numbers on the current line, change it to
:s:\(\d\+\):(\1):g
If you want to change ALL numbers on ALL lines, change it to
:%s:\(\d\+\):(\1):g
You can do what you want with:
:%s/\([0-9]\)/(\1)/
%s means global search and replace, that is do the search/replace for every line in the file. the \( \) defines a group, which in turn is referenced by \1. So the above search and replace, finds all lines with a single digit ([0-9]), and replaces it with the matched digit surrounded by parentheses.

Adding words in front and at the end of line in VIM [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Replace while keeping certain “words” in vi/vim
Let's say I have several lines like
$adv_id;
$am_name;
$campaign_ids;
$repeat_on;
$opt_days;
$opt_time;
$am_or_pm;
Let's say I use visual mode to select all the lines.. how can I add characters at the start and the end of each line so it looks something like
$_REQUEST($adv_id);
$_REQUEST($am_name;
$_REQUEST($campaign_ids);
$_REQUEST($repeat_on;
$_REQUEST($opt_days);
$_REQUEST($opt_time);
$_REQUEST($am_or_pm);
Pretty similar to your other question, so the explanation there should help you to understand this substitute. With the lines selected as a visual block, use this substitute command:
:'<,'>s/\$\(.*\);/$_REQUEST(\1);
As before, the '<,'> will be auto-filled for you in the command-line if you have a visual selection.
The difference here is that we're using \(\) to make a capturing group, which will capture part of the regex, and use it again in the replacement, using \1, which refers to the first capturing group.
Also, since this regex uses $ literally to position the replacement, it needs to be escaped: \$, since it has a special meaning in the regex: end of line.
If you'll need to have multiple replacements on a single line, you'll need to add the g flag, and you may want to remove the semicolon:
:'<,'>s/\$\(.*\);/$_REQUEST(\1)/g
The reverse regex, e.g. replacing $_REQUEST($adv_id); with $adv_id;, is pretty similar:
:'<,'>s/\$_REQUEST(\(.*\))/\1
Here we capture everything between the parens in a $_REQUEST(...); in a capturing group, and that capturing group is the entire replacement.
In visual mode, hit : and use this in the command line:
:'<,'>s/^\(.*\);$/$_REQUEST(\1);/g
The \( and \) capture the matched expression for the line and the \1 recalls the captured group in the substitution.
Using the :'<,'> tells Vim to filter the current selection through the following command (which is s in this case).

Resources