无法使用反引号字符执行所需的替换[关闭]

问题描述 投票:0回答:3

我有一个带反引号的字符串:

this is `some` text

我想用反斜杠在反引号之前:

this is \`some\` text

我试过了:

s/`/\`/g

但这导致原始文本:

this is `some` text

和:

s/`/\\`/g

但这导致双重反斜杠:

this is \\`some\\` text

我尝试过很多其他技巧但没有运气。

regex bash perl
3个回答
2
投票

你的第二个应该工作......

#!/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

0
投票

或者使用带有sed的单衬里

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

说明。

使用字符类[...]来保护您想要替换的字符,然后使用转义"\\"的POSIX形式来逃避您希望包含在替换文本中的实际'\'


0
投票

从没有Data :: Dumper的文件中以单行方式使用它:

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

产量

this is \`some\` text
© www.soinside.com 2019 - 2024. All rights reserved.