How do you find and replace curly braces { } in vim? - vim

I tried :s%/{//g and :s%/\{//g. How do I find and replace (remove, actually) braces in vim?
Thanks.
EDIT: I meant to have the % before the s, so I may have just been mistyping. Thanks everyone for the swift replies.

An extension to #chaos
The { character (ie: left brace, not to be confused with bracket [, or parentheses ( ) ... does not need to be escaped.
You probably mean to remove all braces. The percent symbol should be before the 's', not after. It means to perform the search on all ranges.
So, just do:
:%s/{//g
:%s/}//g
All done!
You should consider reading up on VIM ranges. For example, to do replacements on the current line and up to 10 lines down, you could do:
:.,.+10s/}//g

:s/{//g works fine. Why in the world are you putting that % after the s? By doing that you're indicating % as your regex delimiter character, which is making the rest of your pattern not work because it's written as if / were your delimiter character.
Oh, I see, you mean :%s/{//g.

You should put % before s to replace it in the whole file not only on current line:
:%s/{//g

Related

How can I get the whitespace at the beginning of a line and use it in a search and replace?

Background
I want to convert an if statement from Fortran to C++. I like to have braces on a new line.
So I want to make
! this may be nested so indentation is unknown
if ( condition ) then
block
end if
to
if ( condition )
{
block
}
Changing end if to } is easy since the indentation is already how I want it. I just used :%s/end if/}/gc.
However, changing then is more challenging. I need to create a new line and set its the leading whitespace to the same as the previous line.
The closest I have to a solution is :%s/then/\=printf("\n%s{",indent(line('.')))/gc
However I want to use the value returned from indent(line('.') to set the number of indents.
Problem
Can I use a number I receive from a function to set the number of tabs at the beginning of line in a search and replace?
You want to substitute then with:
a newline,
followed by n spaces, as many as used for indenting the current line,
followed by an opening brace.
As is, your command does the following:
a newline,
followed by the number of spaces used for the indentation of the current line,
followed by an opening brace.
:help repeat() to the rescue:
:%s/then/\=printf("\n%s{",repeat(' ',indent(line('.'))))/gc
But there is still room for improvement…
you only want to substitute trailing thens so the g flag is useless:
:%s/then/\=printf("\n%s{",repeat(' ',indent(line('.'))))/c
the search pattern may match other thens so it should be restricted a little:
:%s/then\s*$/\=printf("\n%s{",repeat(' ',indent(line('.'))))/c
also, the pattern should include any whitespace before the then to avoid leaving annoying trailing whitespace behind:
:%s/\s*then\s*$/\=printf("\n%s{",repeat(' ',indent(line('.'))))/c
line('.') is unnecessary:
:%s/\s*then\s*$/\=printf("\n%s{",repeat(' ',indent('.')))/c
and we could use the new-ish "method" syntax to limit parenthesis nesting:
:%s/\s*then\s*$/\=repeat(' ',indent('.'))->printf("\n%s{")/c

vim search and replace between number

I have a pattern where there are double-quotes between numbers in a CSV file.
I can search for the pattern by [0-9]\"[0-9], but how do I retain value while removing the double quote. CSV format is like this:
"1234"5678","Text1","Text2"
"987654321","Text3","text4"
"7812891"3","Text5","Text6"
As you may notice there are double quotes between some numbers which I want to remove.
I have tried the following way, which is incorrect:
:%s/[0-9]\"[0-9]/[0-9][0-9]/g
Is it possible to execute a command at every search pattern, maybe go one character forward and delete it. How can "lx" be embedded in search and replace.
You need to capture groups. Try:
:%s/\(\d\)"\(\d\)/\1\2/g
[A digit can also be denoted by \d.]
I know that this question has been answered already, but here's another approach:
:%s/\d\zs"\ze\d
Explanation:
%s   Substitute for the whole buffer
\d   look up for a digit
\zs set the start of match here
"     look up for a double-quote
\ze set the end of match here
\d   look up for a digit
That makes the substitute command to match only the double-quote surrounded by digits.
Omitting the replacement string just deletes the match.
You need boundaries to use in regular expression.
Try this:
:%s/\([0-9]\)"\([0-9]\)/\1\2/g
A bit naive solution:
%s/^"/BEGINNING OF LINE QUOTE MARK/g
%s/\",\"/quote comma quote/g
%s/\"$/quota end of line/g
%s/\"//g
%s/quota end of line/"/g
%s/quote comma quote/","/g
%s/BEGINNING OF LINE QUOTE MARK/"/g
A macro can be created quite easy out of it and invoked as many times as needed.

How do you delete all spaces that is 2 char long or more in vim?

I would like to delete every double space in a file open in vim, how is this done?
e.g delete space here
a a
but keep the space here
a a
:%s/\s\{2,}//g
Where the elements are:
%s substitute in the whole file
\s what to substitute: a space
\{2,} two or more occurrences
// replace with nothing (i.e. delete)
g do it on every occurrence on the current line (not only on the first)
The elements shall become clearer if you look at the anatomy of the substitute call:
s/PATTERN/REPLACEMENT/FLAGS
So, the PATTERN in our case is \s\{2,}, the REPLACEMENT is empty and FLAGS are just g. The range gets prefixed and is % which indicates the whole file. If you just want to do it on some lines, you could select the lines visually and then type :s....
Edit:
In your question, you wrote that you want to
delete every double space in a file
That's what I answered. If you want to replace two and more spaces by one, the command would be
:%s/\s\{2,}/ /g
How about this :%s/ */ /g
(there are two spaces in between / and *)
You can do something like:
:%s/\s\s\+/ /g
Although the answer with { is most efficient, I find it easier to remember the space * solution. The correct solution would include three spaces (because * matches 0 or more).
:%s/ */ /g
Of course, this also assumes you want to replace two or more spaces with a single space.

Why do I have to escape the final ]

I have a file containing string like this one :
print $hash_xml->{'div'}{'div'}{'div'}[1]...
I want to replace {'div'}{'div'}{'div'}[1] by something else.
So I tried
%s/{'div'}{'div'}{'div'}[1]/by something else/gc
The strings were not found. I though I had to escape the {,},[ and ]
Still string not found.
So I tried to search a single { and it found them.
Then I tried to search {'div'}{'div'}{'div'} and it found it again.
Then {'div'}{'div'}{'div'}[1 was still found.
To find {'div'}{'div'}{'div'}[1]
I had to use %s/{'div'}{'div'}{'div'}[1\]
Why ?
vim 7.3 on Linux
The [] are used in regular expressions to wrap a range of acceptable characters.
When both are supplied unescaped, vim is treating the search string as a regex.
So when you leave it out, or escape the final character, vim cannot interpret a single bracket in a regex context, so does a literal search (basically the best it can do given the search string).
Personally, I would escape the opening and closing square brace to ensure that the meaning is clear.
That's because the [ and ] characters are used to build the search pattern.
See :h pattern and use the help file pattern.txt to try the following experiment:
Searching for the "[9-0]" pattern (without quotes) using /[0-9] will match every digit from 0 to 9 individually (see :h \[)
Now, if you try /\[0-9] or /[0-9\] you will match the whole pattern: a zero, an hyphen and a nine inside square brackets. That's because when you escape one of [ or ] the operator [*] ceases to exist.
Using your search pattern, /{'div'}{'div'}{'div'}[1\] and /{'div'}{'div'}{'div'}\[1] should match the same pattern which is the one you want, while /{'div'}{'div'}{'div'}[1] matches the string {'div'}{'div'}{'div'}1.
In order to avoid being caught by these special characters in regular expressions, you can try using the very magic flag.
E.g.:
:%s/\V{'div'}[1]/replacement/
Notice the \V flag at the beginning of the line.
Because the square brackets mean that vim thinks you're looking for any of the characters inside. This is known as a 'character class'. By escaping either of the square brackets it lets vim know that you're looking for the literal square string ending with '[1]'.
Ideally you should write your expression as:
%s/{'div'}{'div'}{'div'}\[1\]/replacement string/
to ensure that the meaning is completely clear.

Replacing quote marks around strings in Vim?

I have something akin to <Foobar Name='Hello There'/> and need to change the single quotation marks to double quotation marks. I tried :s/\'.*\'/\"\0\" but it ended up producing <Foobar Name="'Hello There'"/>. Replacing the \0 with \1 only produced a blank string inside the double quotes - is there some special syntax I'm missing that I need to make only the found string ("Hello There") inside the quotation marks assign to \1?
There's also surround.vim, if you're looking to do this fairly often. You'd use cs'" to change surrounding quotes.
You need to use groupings:
:s/\'\(.*\)\'/\"\1\"
This way argument 1 (ie, \1) will correspond to whatever is delimited by \( and \).
%s/'\([^']*\)'/"\1"/g
You will want to use [^']* instead of .* otherwise
'apples' are 'red' would get converted to "apples' are 'red"
unless i'm missing something, wouldn't s/\'/"/g work?
Just an FYI - to replace all double quotes with single, this is the correct regexp - based on rayd09's example above
:%s/"\([^"]*\)"/'\1'/g
You need to put round brackets around the part of the expression you wish to capture.
s/\'\(.*\)\'/"\1"/
But, you might have problems with unintentional matching. Might you be able to simply replace any single quotes with double quotes in your file?
You've got the right idea -- you want to have "\1" as your replace clause, but you need to put the "Hello There" part in capture group 1 first (0 is the entire match). Try:
:%/'\(.*\)'/"\1"
Shift + V to enter visual block mode. Highlight the lines of code you want to remove single quotes from.
Then hit : on keyboard
Then type
s/'//g
Press Enter.
Done. You win.
Presuming you want to do this on an entire file ...
N Mode:
ggvG$ [SHIFT+:]
X Mode:
'<,'>/'/" [RET]

Resources