2

I want to replace a series of pipeline characters with different values. How would I do this with regular expressions?

Example:

This | is | a | sentence
And | this | is | the | second | one

Final result:

This new is new2 a new3 sentence
And new this new2 is new3 the new4 second new5 one
ib.
  • 27,830
  • 11
  • 80
  • 100
help
  • 297
  • 2
  • 5
  • 14
  • Please, rephrase your question adding additional details about desired replacement. – ib. Sep 11 '11 at 06:34

2 Answers2

2

If substitution values differ only in the numbers at the ends, use the command

:let n=[0] | %s/|/\='new'.map(n,'v:val+1')[0]/g

(See my answer to the question "gVim find/replace with counter" for detailed description of the technique.)

In case of substitution values that differ essentially from each other, change the command to substitute not a serial number of an occurrence, but an item of a replacement list with that number as an index.

:let n=[-1] | %s/|/\=['one','two','three'][map(n,'v:val+1')[0]]/g

To perform the substitutions on every line independently of each other, use the :global command to iterate one of the above commands through the lines of a buffer.

:g/^/let n=[0] | s/|/\='new'.map(n,'v:val+1')[0]/g

Similarly,

:g/^/let n=[-1] | s/|/\=['one','two','three'][map(n,'v:val+1')[0]]/g
Community
  • 1
  • 1
ib.
  • 27,830
  • 11
  • 80
  • 100
  • What about multiple lines. I want the same changes throughout multiple lines. adding %s^|/$\...rest of the replace commands, doesnt seem to work. example FROM: This | is | a | sentence This | is | second | sentence This | is | third | sentence TO: This new is new2 a new3 sentence This new is new2 second new3 sentence This new is new2 third new3 sentence – help Sep 13 '11 at 16:23
  • @help: It is easy: just use the `:global` command to iterate the routine over the lines. See the updated answer. – ib. Sep 14 '11 at 01:50
  • Sweet thanks. Still learning about vim commands and regex, so I didnt know of such command. I thought the g flag at the end meant global? again thanks for the help. – help Sep 14 '11 at 14:31
  • @help: The `g` flag of the `:substitute` command prescribes to replace all occurrences in the line, while the `:global` command executes an Ex command on the lines within range of lines where a pattern matches (see `:h :s`, `:h s_flags`, `:h :g`). – ib. Sep 15 '11 at 00:31
0

Define a function:

fun CountUp()
  let ret = g:i
  let g:i = g:i + 1
  return ret
endf

Now, use:

:let i = 1 | %s/|/\="new" . CountUp()/g
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130