在等号周围交换文本 [英] Swap text around equal sign

查看:33
本文介绍了在等号周围交换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在 vi/vim 中翻转等号周围的代码?

例如:我想转这个:

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;
(...)

进入这个:

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;
(...)

在文件中的很多行上.

我知道这看起来有点微不足道,但我在编码时遇到了很多情况,我过去需要这样做,而且我从来没有一个好主意/方法来做到这一点不需要大量输入 vim 或编写 awk 脚本.我认为这可以通过 vi 中的 one liner 实现.

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. :)

推荐答案

是这样的:

:%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.

解释

我们使用 s/find/replace 命令.find 部分让我们知道:

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

  1. 由除等号以外的任何字符组成的最长字符串,用 [^=]* ...
  2. 表示
  3. ... 后跟一个或多个空格,\s\+(+ 前面的额外的 \ 是 vim 的奇葩)
  4. ... 后跟 = 和任意数量的空格,=\s\+
  5. ... 后跟尽可能长的非分号字符串,[^;]*
  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, [^;]*

然后我们放入几个捕获括号来保存我们需要构造替换字符串的内容,那就是 \(stuff\) 语法

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

最后,我们在 s/find/replace 部分使用捕获的字符串em>replace 命令:即 \1\2.

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

这篇关于在等号周围交换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆