简体   繁体   English

使用sed将^ [(s3B替换为空白

[英]using sed to replace ^[(s3B with blank space

I'm trying to use sed with perl to replace ^[(s3B with an empty string in several files. 我正在尝试将sed与perl一起使用,以在多个文件中用空字符串替换^ [(s3B。

s/^[(s3B// isn't working though, so I'm wondering what else I could try. s / ^ [(s3B //无法正常工作,所以我想知道还能尝试什么。

You need to quote the special characters: 您需要引用特殊字符:

 $ echo "^[(s3B AAA ^[(s3B"|sed 's/\^\[[(]s3B//g'
  AAA 

 $ echo "^[(s3B AAA ^[(s3B" >file.txt
 $ perl -p -i -e 's/\^\[[(]s3B//g' file.txt      
 $ cat file.txt 
  AAA 

The problem is that there are several characters that have a special meaning in regular expressions. 问题在于,在正则表达式中有几个具有特殊含义的字符。 ^ is a start-of-line anchor, [ opens a character class, and ( opens a capture. ^是行首锚, [打开一个字符类, (打开一个捕获。

You can escape all non-alphanumerics in a Perl string by preceding it with \\Q , so you can safely use 您可以通过在\\Q前面加上PerQ来转义Perl字符串中的所有非字母数字,因此可以安全地使用

s/\Q^[(s3B//

which is equivalent to, and more readable than 等同于,并且比

s/\^\[\(s3B//

If you're dealing with ANSI sequences (xterm color sequences, escape sequences), then ^[ is not '^' followed by '[' but rather an unprintable character ESC, ASCII code 0x1B. 如果要处理ANSI序列(xterm颜色序列,转义序列),则^ [不是'^'后跟'[',而是不可打印的字符ESC,ASCII代码0x1B。

To put that character into a sed expression you need to use \\x1B in GNU sed, or see http://www.cyberciti.biz/faq/unix-linux-sed-ascii-control-codes-nonprintable/ . 要将字符放入sed表达式中,您需要在GNU sed中使用\\ x1B,或参见http://www.cyberciti.biz/faq/unix-linux-sed-ascii-control-codes-nonprintable/ You can also insert special characters directly into your command line using ctrl+v in Bash line editing. 您还可以在Bash行编辑中使用ctrl + v将特殊字符直接插入命令行。

In regex "^", "[" and "(" (and many others) are special characters used for special regex features, if you are referencing the characters themselves you should preceed them with "\\". The correct substitution reges would be: 在正则表达式“ ^”,“ [”和“(”(以及许多其他字符)中,它们是用于特殊正则表达式功能的特殊字符,如果您引用的是字符本身,则应在它们前面加上“ \\”。正确的替代词为:

$string =~ s/\^\[\(3B//g

if you want to replace all occurences. 如果要替换所有事件。

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

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