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

2019-09-08 18:31发布

This question already has an answer here:

I am trying to replace all digits sequences followed by a line feed and the letter a. Those digits sequences are located in a file called test.txt. The bash script command.sh is used to perform the task (see below).

test.txt

00
a1
b2
a

command.sh

#!/bin/bash

MY_VAR="\d+
a"

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

When I call the command.sh file, here is what I see:

$ ./command
00
a1
b2
a

However, I'm expecting this output:

$ ./command
D1
bD

What am I missing?

1条回答
何必那么认真
2楼-- · 2019-09-08 19:10

You don't even need grep since it is just matching .+, just use perl with -0777 option (slurp mode) to match across the lines:

#!/bin/bash

MY_VAR="\d+
a"

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

Output:

D1
bD
查看更多
登录 后发表回答