如何在Vim中执行搜索/替换,同时保留vim内容?

8fq7wneg  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(175)

我的意思是-
假设我的档案里有这些

ActiveRecord::Base.connection.execute("select * from table1").each_hash do ..
ActiveRecord::Base.connection.execute("select * from table2").each_hash do ..
ActiveRecord::Base.connection.execute("select * from table3").each_hash do ..

client.query("select * from table1").each_hash do ..
client.query("select * from table2").each_hash do ..
client.query("select * from table3").each_hash do ..

字符串
我想用each(:as => :hash)替换onlyActiveRecord的each_hash调用,所以我会得到:

ActiveRecord::Base.connection.execute("select * from table1").each(:as => :hash) do ..
ActiveRecord::Base.connection.execute("select * from table2").each(:as => :hash) do ..
ActiveRecord::Base.connection.execute("select * from table3").each(:as => :hash) do ..


并使client.query行不受影响。
我知道我可以使用宏,但我如何使用Vim的搜索/替换来实现这一点呢?我想使用这个:

%s/\.execute(.*).each_hash/ ...something... /g


问题是,如何在搜索和替换过程中保留实际的查询(what comes where... something... is)?

6mzjoqzu

6mzjoqzu1#

Vim正则表达式中\zs原子的完美用例。这告诉vim在进行替换时忽略\zs之前(包括)的任何内容。

:%s/\.execute(.\{-})\.each\zs_hash/(:as => :hash)/

字符串
\zs的更好解释可以在:help /\zs中找到。

lstz6jyr

lstz6jyr2#

您可以使用global命令进行筛选。

:g/^ActiveRecord/s/each_hash/each(:as => :hash)/g

字符串
键入:help :g以获取帮助:

:[range]g[lobal]/{pattern}/[cmd]
            Execute the Ex command [cmd] (default ":p") on the
            lines within [range] where {pattern} matches.

vs91vp4v

vs91vp4v3#

一个正则表达式来做到这一点:

:%s/\(^\(\(.*client.*\)\@!.\)*\)each.hash/\1each(:as => :hash)/g

字符串
参见^\(\(.*client.*\)\@!.\)*部件的说明:https://vim.fandom.com/wiki/Search_for_lines_not_containing_pattern_and_other_helpful_searches

相关问题