Linux 在 VIM 中搜索和替换导致尾随字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6714469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search and replace in VIM results in trailing characters
提问by Parijat Kalia
This is what I am attempting to do:
这就是我正在尝试做的:
%s/Article/<h2>Article</h2>/gi
Unfortunately, every time i execute this command through my vim editor, it says:
不幸的是,每次我通过 vim 编辑器执行此命令时,它都会说:
Trailing characters
尾随字符
To mitigate the above, I executed the following:
为了缓解上述问题,我执行了以下操作:
%s/\s*\r*$//
And it executes successfully, but when I go back to the original search and replace command, it again reads 'Trailing characters' and does not execute the search and replace operation.
它执行成功,但是当我回到原始搜索和替换命令时,它再次读取“尾随字符”并且不执行搜索和替换操作。
What am I doing wrong here?
我在这里做错了什么?
采纳答案by Merlyn Morgan-Graham
The "trailing characters" are in your command, not your document.
“尾随字符”在您的命令中,而不是您的文档中。
Vim thinks that you finished the command at Article</
, then considers h2>/gi
as the third argument of the substitute command. But those characters aren't all valid for the third argument, so it gives you the error.
Vim 认为您在 处完成了命令Article</
,然后将其h2>/gi
视为替代命令的第三个参数。但是这些字符对于第三个参数并不都是有效的,所以它会给你错误。
To solve this, you need to escape the /
character in your substitute.
要解决此问题,您需要转义/
替代品中的角色。
%s/Article/<h2>Article<\/h2>/gi
回答by Charlie Sanders
Also, if you often need to use literal forward slashes in your regexs (XML/HTML/UNIX file paths) and don't want to worry about escaping every instance, you can use a different delimiter. For example, using ! instead of /:
此外,如果您经常需要在正则表达式(XML/HTML/UNIX 文件路径)中使用文字正斜杠并且不想担心转义每个实例,则可以使用不同的分隔符。例如,使用 ! 代替 /:
%s!Article!<h2>Article</h2>!gi
%s!Article!<h2>Article</h2>!gi
I am lazy and this is usually easier than manually escaping slashes.
我很懒,这通常比手动转义斜杠更容易。