MattB
MattB

Reputation: 31

vim: search, capture & replace on different lines using regex

Relatively new linux/vim/regex user here. I want to use regex to search for a numerical patterns, capture it, and then use the captured value to append a string to the previous line. In other words...I have a file of format:

title: description_id

text: {en: '2. text description'}

I want to capture the values from the text field and append them to the beginning of the title field...to yield something like this:

title: q2_description_id

text: {en: '2. text description'}

I feel like I've come across a way to reference other lines in a search & replace but am having trouble finding that now. Or maybe a macro would be suitable. Any help would be appreciated...thanks!

Upvotes: 0

Views: 192

Answers (3)

Alan Gómez
Alan Gómez

Reputation: 378

For the following example:

title: description_id

text: {en: '2. text description'}

title: description_id

text: {en: '3. text description'}

you can apply the regex:

:%s/\(^.*title: \)\(.*$\n\n.*text: {en: '\)\(\d\+\)\(.*\)/\1q\3_\2\3\4

to transform to:

title: q2_description_id

text: {en: '2. text description'}

title: q3_description_id

text: {en: '3. text description'}

Upvotes: 0

llllvvuu
llllvvuu

Reputation: 286

Perhaps something like:

:%s/\(title: \)\(.*\n\)\(text: \D*\)\(\d*\)/\1q\4_\2\3\4/

Where we are searching for 4 parts:

  1. "title: "
  2. rest of line and \n
  3. "text: " and everything until next digit in line
  4. first string of consecutive digits in line

and spitting them back out, with 4) inserted between 1) and 2).

EDIT: Shorter solution by Peter in the comments:

:%s/title: \zs\ze\_.\{-}text: \D*\(\d*\)/q\1_/

Upvotes: 1

James Doepp - pihentagyu
James Doepp - pihentagyu

Reputation: 1308

Use \n for the new lines (and ^v+enter for new lines on the substitute line): A quick and not very elegant example:

:%s/title: description_id\n\ntext: {en: '\(\i*\)\(.*\)/title: q\1_description_id^Mtext: {en: '\1\2/

Upvotes: 0

Related Questions