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. :)
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:
[^=]*
...\s\+
(the extra \
in front of +
is a vim oddity)=
and again any number of spaces, =\s\+
[^;]*
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With