代码之家  ›  专栏  ›  技术社区  ›  StevieD

无法使用反勾号字符[closed]执行所需的替换

  •  0
  • StevieD  · 技术社区  · 7 年前

    我有一个带背景记号的字符串:

    this is `some` text
    

    我想在反斜杠前面加一个反斜杠:

    this is \`some\` text
    

    我试过:

    s/`/\`/g
    

    但这导致了原文:

    这是一些文字
    

    以及:

    s/`/\\`/g
    

    this is \\`some\\` text
    

    我试过很多其他的把戏,但运气不好。

    3 回复  |  直到 6 年前
        1
  •  2
  •   Shawn    7 年前

    你的第二个应该有用。。。

    #!/usr/bin/perl
    use strict;
    use warnings;
    use feature qw/say/;
    my $string = "a string with `backticks` in it";
    say "Before: $string";
    $string =~ s/`/\\`/g;
    say "After: $string";
    

    生产

    Before: a string with `backticks` in it
    After: a string with \`backticks\` in it
    
        2
  •  0
  •   David C. Rankin    7 年前

    或者用一个内衬 sed

    sed 's/[`]/\\\`/g' file
    

    使用 字符类 [...] 保护要替换的角色,然后使用POSIX转义形式 "\\" '\'

        3
  •  0
  •   Mévatlavé Kraspek    6 年前

    从一个文件中以一行的方式使用它 无数据::转储程序 :

    perl -pe 's/\`/\\`/g' file
    

    输出

    this is \`some\` text
    
    推荐文章