gpt4 book ai didi

regex - vi:::s 如何只替换一行中的第二次出现?

转载 作者:行者123 更新时间:2023-12-04 19:06:43 28 4
gpt4 key购买 nike

:s/u/X/2 - 这将替换当前行和下一行上的第一个 u 到 X ...

或者用 X 替换一行中的第二个字符????身份证。

或者它可能不是 :s ?

我怀疑我必须使用某种分组(\2?),但我不知道该怎么写。

我听说 sed 中的 sed 和 :s 选项很相似,在 sed 的帮助页面上我发现:

3.1.3. Substitution switches:

Standard versions of sed support 4 main flags or switches which may be added to
the end of an "s///" command. They are:

N - Replace the Nth match of the pattern on the LHS, where
N is an integer between 1 and 512. If N is omitted,
the default is to replace the first match only.
g - Global replace of all matches to the pattern.
p - Print the results to stdout, even if -n switch is used.
w file - Write the pattern space to 'file' if a replacement was
done. If the file already exists when the script is
executed, it is overwritten. During script execution,
w appends to the file for each match.

http://sed.sourceforge.net/sedfaq3.html#s3.1.3

所以: :r! sed 's/u/X/2'会起作用,尽管我认为有一种专门的 vi 方法可以做到这一点?

IDK(如果相关)但我使用的是 tcsh shell。

还, :version : Version 1.79 (10/23/96) The CSRG, University of California, Berkeley.

最佳答案

这很脆弱,但可能足以做你想做的事。这个带有正则表达式的 switch 命令:
:%s/first\(.\{-}\)first/first\1second/g
转换这个:

first and first then first again
first and first then first again
first and first then first again
first and first then first again

对此:
first and second then first again
first and second then first again
first and second then first again
first and second then first again

正则表达式查找第一个“第一个”,然后是使用模式 .\{-} 匹配任何字符的匹配项。 ,这是 .* 的非贪婪版本(在 vim 中键入 :help non-greedy 以获取更多信息。)这个非贪婪匹配之后是第二个“第一个”。

第一个和第二个“第一个”之间的字符通过包围 .\{-} 来捕获。带括号,其中,转义结果为 \(.\{-}\) ,然后使用 \1 取消引用该捕获的组(1 表示第一个捕获的组)在替换中。

关于regex - vi:::s 如何只替换一行中的第二次出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775551/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com