bash - 如何从 bash 脚本中将换行符传递给 perl?

bash - How to pass a line feed to perl from within a bash script?

我正在尝试替换所有数字序列,然后是换行符和字母 a。这些数字序列位于名为 test.txt 的文件中。 bash 脚本 command.sh 用于执行任务(见下文)。

test.txt

00
a1
b2
a

command.sh

#!/bin/bash

MY_VAR="\d+
a"

grep -P "^.+$" test.txt | perl -pe "s/$MY_VAR/D/";

当我调用 command.sh 文件时,这是我看到的:

$ ./command
00
a1
b2
a

但是,我期待这样的输出:

$ ./command
D1
bD

我错过了什么?

你甚至不需要 grep 因为它只是匹配 .+,只需使用 perl-0777 选项(slurp 模式)来跨行匹配:

#!/bin/bash

MY_VAR="\d+
a"

perl -0777pe "s/$MY_VAR/D/g" test.txt

输出:

D1
bD