【问题标题】:sed - find a string with special characters and replace in a filesed - 查找带有特殊字符的字符串并在文件中替换
【发布时间】:2018-08-20 14:22:49
【问题描述】:

我很难在包含多个特殊字符的文件中搜索字符串并将整行替换为一些具有特殊字符的文本。

在文件中搜索字符串

a.bb.cc[hk].ccm[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp

替换为

dde.be.cc[hk].com[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp=200

尝试使用 linux sed 但这需要转义所有这些特殊字符,我不想这样做。这些特殊字符可能会因其他字符串而改变。

perl -e "s/$to_replace/$replace_with/g" -pi /tmp/l1 
sed -i -e "s/'$to_replace'/'$replace_with'/g" /tmp/l1

这两个都失败了,因为他们期望转义字符。

我们将不胜感激。谢谢

【问题讨论】:

  • $to_replace$replace_with 是什么?
  • to_replace 是一个具有需要替换的字符串的变量。 $to_replace = "a.bb.cc[hk].ccm[].nib[].gion[].der[].sam[]。 ant[ck].sant[].tags[].rmp" $replace_with = "dde.be.cc[hk].com[].nib[]. gion[].der[].sam[].ant[ck].sant[].tags[].rmp=200"

标签: python perl sed replace find


【解决方案1】:

使用\Q\E 转义序列来禁用模式元字符,即将它们视为要匹配的常规字符。等效地,您可以将搜索字符串放在quotemeta 函数中,然后执行s|$search|$replace|g,这将按您的预期工作。

#!/usr/bin/env perl

use warnings;
use strict;

my $search = 'a.bb.cc[hk].ccm[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp';
my $replace = 'dde.be.cc[hk].com[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp=200';

my $txt = <<EOTXT;
This is some text.
The next line needs replacing...
Inside here: < a.bb.cc[hk].ccm[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp >
More normal text
EOTXT

# perldoc perlre
#  s|...|...|   substitute
# \Q ... \E     quote (disable) pattern metacharacters till \E
#
# modifiers:
# s             treat string as single line
# g             global

$txt =~ s|\Q$search\E|$replace|sg;
print $txt;

输出

This is some text.
The next line needs replacing...
Inside here: < dde.be.cc[hk].com[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp=200 >
More normal text

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    相关资源
    最近更新 更多