Questions tagged [substitute]

Any operation involving regular expression based substitution of text, such as the ex-mode `:s` command. Not to be confused with the [replace] tag.

Filter by
Sorted by
Tagged with
68
votes
12answers
17k views

How to find and replace in Vim without having to type the original word?

I'd like to optimize my "find and replace" workflow in Vim. It's something I do often, as I'm sure most of you do too. Usually something along the lines of -- copy a block and change the name of a ...
42
votes
3answers
109k views

Find and replace using regular expressions

I have a file with a bunch of user defaults in. I want to change some of the text, but I'm struggling coming up with a matcher and replacer. Using the following example: ##############################...
39
votes
4answers
11k views

How to replace only within visual selection?

How does one get vim to replace a character within the visual selection only and not elsewhere on the line? Example: Line: int arr[] = { 00 01 02 03 04 05 05 /* ... lots more like this*/}; Visual ...
25
votes
1answer
10k views

How to edit files non-interactively (e.g. in pipeline)?

I would like to edit files passed in pipeline input using vim in non-interactive way or edit files in-place (similar to sed). Few examples using sed: $ sed -i'.bak' s/foo/test/g file # Edit file ...
21
votes
5answers
9k views

Can I do an interactive :substitute (search & replace)?

Sometimes I use :s with a complicated regexp which may or may not be correct, or I'm not sure if I want to replace all matches. Is there any way I can tell Vim to confirm every match it finds before ...
21
votes
1answer
214 views

How does :g/^$/,/./-j (reduce multiple blank lines to a single blank) work in vim?

In the article, Vim Regular Expressions, Oleg Raisky gives the following command to reduce multiple blank lines to a single blank: :g/^$/,/./-j Can someone please describe how this works? I know :...
19
votes
2answers
2k views

Replace a string without changing case?

Due to a quirk in the domain-specific language I am working with, I frequently face the task of (selectively, not globally) replacing term or TERM with word or WORD, respectively. This means, I ...
16
votes
5answers
1k views

Replace a series of asterisk bullet points with a numbered list

Imagine I have the following text: some random stuff * asdf * foo * bar some other random stuff I want to replace the asterisk bullets with numbers, like so: some random stuff 1. asdf 2. foo 3. bar ...
16
votes
3answers
395 views

Can I make :s operate only on the last match of the line?

:s/pattern/replacement operates on the first match and :s/pattern/replacement/g on all. How to operate only on the last one?
16
votes
1answer
1k views

What does it mean to replace slashes (/) by exclamation marks (!) in a substitute command?

I recently saw a substitute command where the author had the / replaced by a ! like this: :s!abc!ABC!g I tried to find some documentation on this usage but I couldn't find anything relevant. So I ...
16
votes
2answers
2k views

Vim global substitution doesn't substitute all matches in a line

Sometimes my global substitutions don't substitute all matches in a line. It is confirmed by the fact that I can see it when I do substitutions with confirmation, a match is found in a line with ...
15
votes
5answers
14k views

How to replace each match with incrementing counter?

I want to search and replace each occurrence of a certain pattern with a decimal number which begins at 1 and increments by one for each match. I can find similarly worded questions that turn out not ...
15
votes
3answers
8k views

Substitute with pure vimscript (without `:s`)

I have the following in my vimrc: func! AddSpaceBeforeEqual() s/\([a-z)_0-9"'\[\]]\)=/\1 =/ge endfunc I'm using vint to lint my vimrc, and got the following warning : ...
15
votes
2answers
551 views

Multiple choice substitute?

Normally, a substitute with the c option gives me two options: (y)es or (n)o. Is it possible to have several numbered yes options to choose from? Example File person: Alice dog: Tobby person: Bob ...
15
votes
2answers
467 views

How can I run :substitute on only part of the line and not all of it?

I have a line like this one: function my_function(argument, another argument, but there are spaces) I want to substitute the space characters (inside the argument's names) with underscore. I thus ...
15
votes
4answers
2k views

What is the rationale for \r and \n meaning different things in s command?

We all know that, when searching, \n is newline and \r is carriage return (^M), but when replacing \r is newline while \n is a null byte (^@). What is the origin of this asymmetry? Given that this ...
13
votes
11answers
10k views

Substitute second occurence on line

I have a list of files: ./a.temp.txt ./a.temp.txt ./a/b.temp.txt ./a/b.temp.txt ./a/b/c.temp.txt ./a/b/c.temp.txt And I want to remove the temp. on each line, but only the second occurence, ...
13
votes
6answers
3k views

Delete all consecutive duplicates

I have a file that looks like this. Move to 230.00 Hold Hold Hold Hold Hold Hold Move to 00.00 Hold Hold Hold Hold Hold FooBar Hold Spam Hold I would like it to look like this: Move to 230.00 ...
11
votes
6answers
2k views

How to append some line at the end of the file only if it's not there yet?

I'd like to edit a file in-place by appending a line, only if doesn't exist yet to make my script bullet-proof. Normally I'd do something like: cat >> ~/.bashrc <<EOF export PATH=~/....
11
votes
1answer
1k views

Apply normal mode command to regex matches

I am using the following regular expression to match a documentation string underneath a Clojure function definition: \vdefn.*\n\s*\zs"([^"]|\n)*" Is there a way to run the normal mode gq (format ...
10
votes
5answers
2k views

How to run a substitute command on only a certain part of the line

I have the following line in my code: INCORRECT_EMAIL_MOBILE_COMBINATION("incorrect_email_mobile_combination"); When I try to substitute the underscores with spaces in visual mode (using :'<,'>...
10
votes
4answers
275 views

Restricting operations to a section of code

There is many times in my day to day work life that I need to operate on a specific function, things like highlighting or searching for a variable, but I have never managed to limit the scope of the ...
10
votes
1answer
1k views

How to substitute in multiple lines?

I'd like to insert a word in multiple lines, is there any command like :[2,3,5,7,11]s/^/word\ /g which would insert word at the beginning of line 2, line 3, line 5, line 7 and line 11? Here, ...
10
votes
1answer
1k views

How can I execute multiple optional substitute commands in one line?

I am comparing a couple of files with vimdiff. There are some differences which I expect and which I'd like to get rid of. I know I can use: :%s#from1#to1#g | %s#from2#to2#g | ... to replace ...
9
votes
1answer
1k views

How to get a preview for the substitution command?

Quite often I find myself in need of performing a substitution that will have matches sparsed all over a large file and with non-trivial search and replacement expressions. For example, say I have ...
8
votes
3answers
4k views

What is the best way to re-factor a variable name in vim?

I know there is one way to search and replace variable occurrences across a source file. But is there any better way by which if I rename a variable at one place it gets renamed at other places as ...
8
votes
2answers
209 views

Is there a shortcut to reuse the search term of the find and replace?

I think there is a distinct possibility this question has already been asked, but I can't find it. If I am doing something like :s/foo/bar/g and then I want to call that again on the next line but ...
8
votes
1answer
234 views

Perform previous substitution for different selection with single keystroke

I performed following command :'<,'>s/2/digit/g on the code below manually visually selected: return _.round(this.getTotalAbs(), 2).toFixed(2); And it worked as intended return _.round(...
8
votes
1answer
16k views

Find and replace all numbers with 0?

Is there a command to find and replace all instances of a number in a file with 0 (including decimal numbers like 1.7)?
8
votes
1answer
3k views

How to translate Unicode escape sequences to the Unicode character?

I have a file with a lot of characters represented like this: \u05E2. (These are the actual characters in the file: backslash, lowercase u, and four hexadecimal digits.) Due to that, the file is ...
8
votes
1answer
1k views

How do I replace a character with its hex value?

I want to replace a character with its hex literal. For example before regex: h After regex: 0x68 I'm trying this: s/\([a-z]\)/\=printf("%#02x", submatch(0))/ But this replaces it with 00 ...
7
votes
2answers
2k views

How to use substitution on register?

Let say I've register which has string stored in it, but I'd like to use substitute command to change it. For example I've 5x5 html table: let @t='<table>'.repeat('<tr>'.repeat('<td&...
7
votes
2answers
3k views

How to repeat last action with movement?

Assume the content: foo fnord bar;" >> /tmp/foo/derp gnarf foo fnord bar;" >> /tmp/foo/derp I want to jump to the " and delete to end of line and repeat that over the rest of lines. Yet ...
7
votes
1answer
2k views

How can I repeat last substitution and with the same flags

& repeats the last :s But it doesn't repeat with flags, e.g. a global sub: :s/"/'/g won't replace in the same way on consecutive lines with &, running :s/"/'/g on the first line here and ...
7
votes
4answers
4k views

Replace with hex character

Given this file: printf 'hello\x19world\n' > hello.txt I can replace a hex character: $ ex -sc '%s/\%x19/ /|x' hello.txt $ od -c hello.txt 0000000 h e l l o w o r l d \n ...
7
votes
1answer
801 views

Replace all occurrences in visual block selection but NOT all occurrences on line

I'm trying to figure out how to do a search and replace on a visual block selection that will replace all occurrences in the visual block selection without replacing all occurrences on the line. What ...
6
votes
4answers
8k views

How to delete part of a line that does not match a pattern?

I'd like to remove everything apart of my pattern match. For example I've the following line: window.page4_callback(["here \"is\" some text"]); and I'd like to leave the text only within the double ...
6
votes
2answers
496 views

What is the most efficient way to invert two words?

Let's say that I have a file containing several occurrences of the word foo and several occurrences of the word bar. I need to make all the words foo become bar and inversely all the words bar become ...
6
votes
3answers
4k views

Multiple search-replace operations on a selection

I have a LaTeX file with a bunch of commands of the form \label{<word>} where the <word> represents a string that contains special characters, namely á é í ó ú ý ð þ æ ö. I'm looking for a ...
6
votes
4answers
524 views

How can I store a series of regular expression search and replace commands and run them later?

How can I store a series of search and replace statements so I can run them later in sequence? Possibly after I have close and re-opened vim... For instance I might run the following in sequence ...
6
votes
2answers
11k views

How to replace bracket in vim?

I have "012-0738-32"],[ "4", "Beacon I want "012-0738-32" "4", "Beacon ],[+ space replaced with \r
6
votes
3answers
3k views

regex: how to replace “\[”?

I have this sample line in the buffer: export PS1="\[${Cyan}\]$(((SHLVL>1)) && echo "${SHLVL}\[${IBlack}\].")\[${IGreen}\]\u\[${IBlack}\]@\[${Purple}\]\h\[${IYellow}\] \w \$ \[${Color_Off}\...
6
votes
1answer
2k views

When substituting with :%s/old/new/g, does g flag have any effect?

While working through vimtutor, I tried a variant on :%s/old/new/g by leaving off the g flag :%s/old/new and expected the substitution to only occur once in the whole file. After all, this mirrors ...
6
votes
1answer
712 views

How to make substitute() use another magic mode?

The doc about the substitute function :h substitute() tells us: [...] the matching with {pat} is always done like the 'magic' option is set [...] That's cool but what if I need to use substitute() ...
6
votes
1answer
282 views

How do I capitalize the first word after each period, question mark or exclamation point?

I would like to know the proper substitution command in vi that would accomplish this.
6
votes
1answer
945 views

Search and replace: float arithmetic

For example I have many numbers like 111.222, I want to decrease them to 0.1 (to get 111.122), how to do that? I tried: :%s#\d\+\.\d\+#\=submatch(0)-0.1# But as a result I have 110.9.
6
votes
1answer
127 views

How to prevent stopping a macro on unsuccessful substitution?

I've been trying to record a rather simple macro with two substitutions. The whole macro is: dd"+pkdd:%s/\t/, /g :%s/ \(kb\d\+\),/ \1.0,/g "+y$ However, the second substitution is there to reformat ...
6
votes
1answer
116 views

Convert word to another substituting case (upper or lower) with same case

I am looking for a way to convert one word to another while "capturing" the case of the match that is substituted. An example: I have the text: Begin the beginning Now I want to convert this to ...
5
votes
3answers
7k views

Replace Nth Occurrence Using Substitute

Here is my data: { team: 'NYY', result: 'L', rs: 1,6 }, { team: 'NYY', result: 'W', rs: 4,3 }, { team: 'NYY', result: 'L', rs: 3,6 }, { team: 'NYY', result: 'L', rs: 5,6 }, { team: 'NYY', result: 'L',...
5
votes
5answers
5k views

Match any number of digits NOT followed by

I want to search for: From start of the line, any number of white spaces followed by any number of digits NOT followed by a dot. And replace it with all that was searched and a dot. This is just ...

1
2 3 4 5 6