简体   繁体   English

sed,替换#include中的反斜杠

[英]sed, replace backslash in #include

I wish to replace all the backslashes (which appear on the same line with an include directive) with slashes. 我希望用斜杠替换所有反斜杠(与include指令在同一行上出现)。

Here's what I have until now.. 这是我到现在为止所拥有的......

echo '#include "..\etc\filename\yes"' | sed 's&\(#include.*\)\\&\1\/&g'

This works as I expect, but the problem is that it replaces only one \\ at a time... If I want to replace all three in the above text, I have to run the sed command 3 times... The g flag at the end should make the replacements globally, no? 这可以按照我的预期工作,但问题是它一次只替换一个\\ ...如果我想在上面的文本中替换所有三个,我必须运行sed命令3次... g标志在最终应该在全球范围内进行替换,不是吗?

I'm using sed 4.2.1 on Ubuntu 11.10... 我在Ubuntu 11.10上使用sed 4.2.1 ...

The problem is the way you're matching. 问题是你的匹配方式。 The .* is greedy, so it matches the last backslash first and then thinks it's done. .*是贪婪的,所以它首先匹配最后一个反斜杠然后认为它已经完成了。 Try this: 尝试这个:

... | sed '/^#include/s&\\&/&g'

That runs the substitutions only on lines matching the first pattern. 仅在与第一个模式匹配的行上运行替换。

你想要一个复合命令 - 第一个模式匹配以#include开头的行,第二个模式匹配你的斜杠翻译。

sed '/^#include/ s&\\&/&g'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM