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.
source to share
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.
source to share