How to ignore inconsistencies in find / replace perl sed-like command?

Given this simple sed command:

echo "abc\nxyz" | sed "s/abc/***/"

      

Equivalent version of Perl

echo "abc\nxyz" | perl -pe "s/abc/***/" 

      

Sed allows me to output only matching lines:

echo "abc\nxyz" | sed -n "s/abc/***/p"

      

How do I do this with Perl?

FYI, I want to use the Perge regex engine, which seems to be more complete than sed, but I need this sed option.

+3


source to share


2 answers


In Perl, a switch -p

sets up an implicit loop that $_

iterates over the input and prints the content after each iteration of the loop. Perl also has a switch -n

that requires code inside this implicit loop to process its own output:

echo "abc\nxyz" | perl -ne 's/abc/***/ && print'

Switches -p

and are -n

described in perlrun .

In short, it -p

forms an implicit loop that looks something like this:



while( <> ) {
    # Your code goes here...
}
continue {
    print;
}

      

And it -n

forms an implicit loop that looks something like this:

while( <> ) {
    # Your code goes here....
}

      

So with -n

, you have to explicitly specify when to output and what that output should be. By taking back control of the output, you can enable logic that allows you to "print" only when certain conditions are met, such as regular expression matching. In my example, we are using a boolean short circuit to trigger printing if the match is successful.

+1


source


An option -p

for Perl is to do the action -e ...

on each line of input and then print. Jumping to -n

means reading each line of the file and executing -e ...

for each. So a simple way to achieve the waht you want:



echo "abc\nxyz" | perl -ne "print if s/abc/***/"

      

+3


source







All Articles