Krishh
Krishh

Reputation: 33

how to replace a word combined with special character in vi editor

I am exploring vi editor,

I want to replace _ (underscore) with [] bracket.

Example: data_0 needs to be replaced with data[0].

I know basic replace command in vi. How can I replace in this situation?

Upvotes: 0

Views: 435

Answers (2)

Stun Brick
Stun Brick

Reputation: 1254

Just to expand on gaganso's answer, and explain what

:%s/_\(\d\+\)/[\1]

means.

  • : its an ex command
  • % across the entire file
  • s it's a substitution

substitutions come in the following format (see :help :s)

:[range]s/[find]/[replace]/[flags]

we've already handled the range (its global, thanks to %), now we just need to explain what's inside the [find] and the [replace] blocks.

the [find] part of this regex is

_\(\d\+\)

and it says

  • _ find an underscore
  • \( open a new grouping (escaped brackets indicates that whatever we find inside should be 'saved' so we can put it back in later)
  • \d+ look for any number of digits in a row
  • \) close grouping (so the part that we 'saved' for later is any number of digits in a row, that come after an underscore. In your example this would be the 0 of data_0

And the [replace] section

  • [ put down a square bracket
  • \1 put down whatever it is we saved in our grouping (the 1 indicates we are taking whatever was found in the first grouping, we also happen to only have one grouping anyway)
  • ] put down another square bracket

And there you have it! The vim regex for finding an underscore followed by a number, and replacing it with the same number inside square brackets!

Upvotes: 4

gaganso
gaganso

Reputation: 3011

The below command should work. It captures the index following the _ using parenthesis.

:%s/_\(\d\+\)/[\1]

\1 provides the first captured group which is the number following _.

Upvotes: 6

Related Questions