Swap text around equal sign

安稳与你 提交于 2019-12-02 18:33:16

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.

For interest's sake, here's how I did it as a recorded macro:

qq0"+df=xA<BACKSPACE> = <ESC>"+pxi;<ESC>jq

Peforming that on the first line sets the "q" macro to do what's required. Then on each subsequent line you can execute the macro by typing:

@q

or, say you want to apply the macro to the next 10 lines:

10@q

I always find macros easier for a quick switch like this than figuring out the regex, because they're essentially an extension of how I would do it by hand.

Edit: Dan Olson points out in his comment that if you want to then apply the macro to a range of lines, for instance lines 6-100, you can enter the following. I don't know if there's a more concise syntax that doesn't require the ".*" pattern match.

:6,100g/.*/normal @q

Explanation of the macro

  • qq
    • start recording in register q
  • 0
    • go to beginning of line
  • "+df=
    • delete up to the '=' and put the text into the '+' register
  • x
    • delete extra space
  • A
    • go to end of line and enter insert mode
  • <BACKSPACE> = <ESC>
    • Delete the semicolon, insert an equals sign and a space
  • "+p
    • insert the test copied earlier into register '+'
  • xi;<ESC>
    • reinsert the trailing semicolon
  • j
    • move down to the next line, ready to reapply the macro
  • q
    • stop recording
:%s/^\s*\(.\{-}\)\s*=\s*\(.\{-}\)\s*;\s*$/\2 = \1;/

should work nicely.

:%s/\([^ =]*\)\s*=\s*\([^;]*\);/\2 = \1;/
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!