Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap text around equal sign

Tags:

vim

vi

Is there an easy way to flip code around an equal sign in vi/vim?

Eg: I want to turn this:

value._1 = return_val.delta_clear_flags;
value._2._1 = return_val.delta_inactive_time_ts.tv_sec;
value._2._2 = return_val.delta_inactive_time_ts.tv_nsec;
value._3    = return_val.delta_inactive_distance_km;
(...)

into this:

return_val.delta_clear_flags = value._1;
return_val.delta_inactive_time_ts.tv_sec = value._2._1;
return_val.delta_inactive_time_ts.tv_nsec = value._2._2;
return_val.delta_inactive_distance_km = value._3;
(...)

on A LOT of lines in a file.

I know this seems a little trivial, but I've been running into lots of cases when coding where I've needed to do this in the past, and I've never had a good idea/way to do it that didn't require a lot of typing in vim, or writing a awk script. I would think this would be possible via a one liner in vi.

Explanations of the one-liners is very welcome and will be looked upon highly when I select my accepted answer. :)

like image 505
J. Polfer Avatar asked Sep 03 '09 15:09

J. Polfer


1 Answers

Something like this:

:%s/\([^=]*\)\s\+=\s\+\([^;]*\)/\2 = \1

You might have to fiddle with it a bit if you have more complex code than what you have shown in the example.

EDIT: Explanation

We use the s/find/replace comand. The find part gets us this:

  1. longest possible string consisting of anything-but-equal-signs, expressed by [^=]* ...
  2. ... followed by one or more spaces, \s\+ (the extra \ in front of + is a vim oddity)
  3. ... followed by = and again any number of spaces, =\s\+
  4. ... followed by the longest possible string of non-semicolon characters, [^;]*

Then we throw in a couple of capturing parentheses to save the stuff we'll need to construct the replacement string, that's the \(stuff\) syntax

And finally, we use the captured strings in the replace part of the s/find/replace command: that's \1 and \2.

like image 135
Arkady Avatar answered Oct 28 '22 23:10

Arkady