Paradigm
Paradigm

Reputation: 149

Vim - Vi // Substitute pattern

I have an XML file as follows:

<Word name="name1" WordID="...">
</Word>

I need to insert 2 extra leading spaces in front of both such lines, in the whole file Any ideas? - Thanks!

Upvotes: 1

Views: 449

Answers (2)

D. Ben Knoble
D. Ben Knoble

Reputation: 4703

Alternative: global command.

Global commands act on the entire file, and perform an (Ex) action on each line that matches the pattern. It’s the inspiration for grep (:global/re/print), and resembles awk if you squint.

Our action here is to insert two spaces, which, semantically, is less-well captured by a substitute to my brain.

Since we need an Ex command, we use :normal! to execute a normal command with no mappings applied, and then simply Insert two spaces at the beginning of the line.

(I copied and edited the pattern from N Sarj’s answer)

:global ~</\?[Ww]ord~ normal! I  

Take care to note the two trailing spaces after I.

Here I used ~ as a pattern separator because any character will do, and not using the standard / meant I didn’t need to escape it in the pattern.

We still must escape the ? to get it’s special meaning of “zero or one” (as opposed to matching a literal ?).

Upvotes: 1

N Sarj
N Sarj

Reputation: 434

Try:

%s/^\(<\/*[Ww]ord.*\)$/  \1/

% means whole file.

s means substitute

^ means start of line

$ means end of line

< is the angle bracket

.* means any character zero or more times

( and ) enclose the regular expression you want to keep

\1 indicates where the regular expression kept should be inserted.

After / and before \1 you insert as many spaces as you want.

When you write an expression between \( and \) it is recorded and can be used afterwards with \N where N is a number. For example here \1 means the first expression matched. If you had \( and \) a second time, you could use \1 and \2 to include the first and the second one respectively.

For example,

s/\(first\)\(second\)/\1 \2/

will insert a space between the words first and second

Upvotes: 2

Related Questions