我有一个带反引号的字符串:
this is `some` text
我想用反斜杠在反引号之前:
this is \`some\` text
我试过了:
s/`/\`/g
但这导致原始文本:
this is `some` text
和:
s/`/\\`/g
但这导致双重反斜杠:
this is \\`some\\` text
我尝试过很多其他技巧但没有运气。
你的第二个应该工作......
#!/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
或者使用带有sed
的单衬里
sed 's/[`]/\\\`/g' file
说明。
使用字符类[...]
来保护您想要替换的字符,然后使用转义"\\"
的POSIX形式来逃避您希望包含在替换文本中的实际'\'
。
从没有Data :: Dumper的文件中以单行方式使用它:
perl -pe 's/\`/\\`/g' file
this is \`some\` text