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::/:

      

+3


source to share


4 answers


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

      

+10


source


You only need one print

; do not put in two more tees!

perl -ne 'print /root/ ? "\#$_" : $_' </etc/passwd

      



Be that as it may, you are unconditionally printing the return value of whatever print

the ternary operator does - hence 1

.

+8


source


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

      

+3


source


How about just

perl -pe 'print "#" if /root/' /etc/password

      

Which prints each line anyway due -p

, but also prints the hash character first if the regex matches

+2


source







All Articles