one-liners beginner
How to delete lines matching a pattern with perl one-liner?
Question
How to delete lines matching a pattern with perl one-liner?
How to Delete Lines Matching a Pattern with a Perl One-liner
In Perl, deleting lines that match a pattern is typically done by processing input line-by-line and selectively printing only those lines that do not match the pattern. The common command-line switches are:
-n: wraps the code in a loop over each input line but does not print automatically-p: same as-n, but prints each line after the code block runs
To remove lines matching a pattern, you can:
- Use
print unless /pattern/with-n, e.g.perl -ne 'print unless /error/' file.txt - Use
next if /pattern/;with-p, e.g.perl -pe 'next if /error/' file.txt
However, in sandbox environments without file or standard input access, you must simulate input lines inside the Perl script itself.
Runnable Perl Example (Self-contained, No File or Input Needed)
This example stores sample lines in an array and prints only those which do not contain the substring error. It runs directly with perl - and shows how to filter lines in Perl without external input:
use strict;
use warnings;
# Sample input lines
my @lines = (
"System running smoothly\n",
"Warning: error detected\n",
"All checks passed\n",
"Fatal error encountered\n",
);
foreach my $line (@lines) {
# Print lines that do NOT match 'error' (case-sensitive)
print $line unless $line =~ /error/;
}
This script uses:
@linesarray to simulate reading multiple linesforeachloop to iterate through each lineprint unless $line =~ /error/to skip lines containing the pattern
Perl Concepts and Gotchas
- Sigils:
$for scalars (e.g.,$line),@for arrays (e.g.,@lines), reflecting variable context - Default variable
$_: In Perl one-liners, each line is placed in$_automatically, enabling concise pattern matching likeprint unless /pattern/. - Context: The
-nswitch provides a loop over input without printing;-padds automatic printing at loop end. - TMTOWTDI ("There's more than one way to do it"): You can use either explicit
printwith conditional ornextto skip lines. - Regex case sensitivity: Use
/pattern/ito match ignoring case. - Common pitfall: Trying to run one-liner code without providing input files or input streams causes errors (as your environment lacks those).
Summary
- To filter lines from files or stdin, use Perl one-liners with
-nor-pand conditional printing/skipping. - In restricted sandbox contexts without file or stdin access, simulate input with an array inside a Perl script.
- Learn Perl’s loop switches (
-n,-p) and the default$_variable for idiomatic text processing.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 9ms
Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
System running smoothly
All checks passed
STDERR
(empty)