Why does "print / regex /? Print a: print b" put "1" in front of each line?
When I run the bottom one-liner Perl, it prints 1
before every line I don't want to. All you have to do is comment lines that match root
.
$ cat /etc/passwd | perl -ne 'print /root/ ? print "\#$_" : print $_'
1daemon:x:1:1::/:
1bin:x:2:2::/usr/bin:
#root:x:0:0:Super-User:/root:/usr/bin/bash
1sys:x:3:3::/:
source to share
You are printing a return value print
that succeeds, so it matters 1
.
I would suggest changing your code to this:
perl -pe '$_ = "#$_" if /root/' /etc/passwd
Here I am using a switch -p
, so it $_
always prints. A is #
appended to the beginning of the line when it /root/
matches.
If you want to specify explicitly print
, use this:
perl -ne 'print /root/ ? "#$_" : $_' /etc/passwd
source to share
You get a leading 1
on each line because it is the result of the evaluation /root/ ? case_true : case_false
.
To fix this problem, just get rid of the initial print
before /root/
:
cat /etc/passwd | perl -ne '/root/ ? print "\#$_" : print $_'
# ^
# no print!
Please note that there is no need cat file | perl
. Instead, say perl file
:
perl -ne '/root/ ? print "\#$_" : print $_' /etc/passwd
source to share