Hyder Tom
Hyder Tom

Reputation: 373

replace a string with other string in the same line

Vi editor

Input file text format:

'': hello.Code1
'': hello.Code2
'': hello.Code3

Required output text format:

'Code1': hello.Code1
'Code2': hello.Code2
'Code3': hello.Code3

Idea is I have to copy all the values after "." to the single quotes ''. I can use Vi or SED etc. Linux based. or MAC based. I have more that 2000 lines in the text file Thanks

Upvotes: 1

Views: 751

Answers (2)

DJMcMayhem
DJMcMayhem

Reputation: 7679

This can be done quite simply with a substitute command and capturing groups. Try the following regex:

:%s/''\(.*\)\.\(.*\)/'\2'\1.\2

This says, Search for quotes '', followed by anything captured into group 1 \(.*\), followed by a literal dot \., followed by anything captured into group 2 \(.*\). This will put

: hello

Into group 1, and

CodeN

into group 2. So then we replace it with group 2 in quotes '\2' followed by group 1 \1, followed by a dot \. and group 2 again \2.

If you put \v at the beginning of the regex, you can get rid of a lot of the backslashes and make it more readable:

:%s/\v''(.*)\.(.*)/'\2'\1.\2

You could also do this with a %normal command. That makes a set of keystrokes be applied to every line in the buffer. I would try this:

:%norm f.ly$0p

This says, On every line, do the following keystrokes :%norm Move forward to a '.' f., move one character to the right l, yank everything to the end of this line y$, move to the beginning of this line 0, and paste what we just yanked p

Upvotes: 1

Bijay Gurung
Bijay Gurung

Reputation: 1104

You can use a macro in vim. Something like:

/\.^Mly$?'^MPj0

Assuming you're at the start of the first line. Start recording. To record into the q register, hit qq and then:

i) Search for the dot

/\.^M

ii) Go one character to the right, and yank to the end of the line

ly$

iii) Reverse search the quote: '

?'^M

iv) Paste the content and go down a line and move to the start.

Pj0

You can then just repeat the action. Assuming you recorded it in the q register:

2@q

(Note: ^M is <Enter>)

Action Gif

Upvotes: 1

Related Questions