Reputation: 31
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
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
Reputation: 286
Perhaps something like:
:%s/\(title: \)\(.*\n\)\(text: \D*\)\(\d*\)/\1q\4_\2\3\4/
Where we are searching for 4 parts:
"title: "
\n
"text: "
and everything until next digit in lineand 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
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