Search code examples
regexlinuxbashperllinefeed

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


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?


Solution

  • 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