Linux 带有特殊字符的 sed

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5980857/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:03:04  来源:igfitidea点击:

sed with special characters

linuxbashunixsed

提问by shd

I have this line that I want to use sed on:

我有这条线,我想在上面使用 sed:

--> ASD = $start ( *.cpp ) <--

where $start is not a varaiable, I want to use sed on it and replace all this line with:

$start 不是变量,我想在它上面使用 sed 并将所有这一行替换为:

ASD = $dsadad ( .cpp ) 

How can I make sed ignore special charactars, I tried adding back slash before special characters, but maybe I got it wrong, can some one show me an example?

如何让 sed 忽略特殊字符,我尝试在特殊字符前添加反斜杠,但也许我弄错了,有人可以给我举个例子吗?

Here is what i want :

这是我想要的:

sed 's/CPPS = $(shell ls | grep \*\.cpp )/somereplace/' Makefile

采纳答案by Cédric Julien

sed 's/$start/$dsadad/g' your_file
>> ASD = $dsadad ( *.cpp ) 

sed 's/\*//g' your_file
>> ASD = $start ( .cpp ) 

To follow your edit :

要遵循您的编辑:

sed -i 's/ASD = $start ( \*.cpp )/ASD = $dsadad ( .cpp )/' somefile
>> ASD = $dsadad ( .cpp )

Add the -i (--inplace) to edit the input file.

添加 -i (--inplace) 以编辑输入文件。

回答by sapht

Backslash works fine. echo '*.cpp' | sed 's/\*//'=> .cpp

反斜杠工作正常。echo '*.cpp' | sed 's/\*//'=>.cpp

If you're in a shell, you might need to double escape $, since it's a special character both for the shell (variable expansion) and for sed (end of line)

如果您在 shell 中,则可能需要双重 escape $,因为它是 shell(变量扩展)和 sed(行尾)的特殊字符

echo '$.cpp' | sed "s/\\$//"or echo '$.cpp' | sed 's/\$//'=> '.cpp'

echo '$.cpp' | sed "s/\\$//"echo '$.cpp' | sed 's/\$//'=> '.cpp'

Do not escape (or ); that will actually make them them special (groups) in sed. Some other common characters include []\.?

不要逃避(); 这实际上会使他们在 sed 中变得特别(组)。其他一些常见字符包括[]\.?

This is how to escape your example:

这是逃避您的示例的方法:

sed 's/ASD = $start ( \*\.cpp )/ASD = $dsadad ( .cpp )/' somefile

回答by glenn Hymanman

The chacters $,*,.are special for regular expressions, so they need to be escaped to be taken literally.

该chacters $*.是特殊的正则表达式,所以他们需要逃到字面上理解。

sed 's/ASD = $start ( \*\.cpp )/ASD = $dsadad ( .cpp )/' somefile