perl one line script with condition - perl

I have some text file. E.g.
1;one;111
2;two;222
22;two;222
3;three;333
I try to select line that contains "one" using perl-oneliner:
perl -F";" -lane 'print if $F[1]=="one"' forPL.txt
But I get all lines from file.
I don't need use regular expression(reg exp helps in this case), I need exactly match on second field.
Thank you in advance

Use eq for string comparison instead of == which is used for numeric comparison.
perl -F";" -e 'print if $F[1] eq "one" ' test.txt
Edit: As toolic has suggested in his comment, if you had used warnings, you could have easily spot the issue.
$ perl -F";" -e 'use warnings; print if $F[1] == "one" ' test.txt
Argument "one" isn't numeric in numeric eq (==) at -e line 1, <> line 1.
Argument "one" isn't numeric in numeric eq (==) at -e line 1, <> line 1.
1;one;111
Argument "two" isn't numeric in numeric eq (==) at -e line 1, <> line 2.
2;two;222
Argument "two" isn't numeric in numeric eq (==) at -e line 1, <> line 3.
22;two;222
Argument "three" isn't numeric in numeric eq (==) at -e line 1, <> line 4.
3;three;333

Related

Inserting a line in text file through perl is failing

I am trying to insert a new row on 2nd line of text file using perl . But it keeps failing.
I am using below command to achieve the same.
perl -ni -e "print; print \"permissibleCars = [ ${part[*]} ]\n\" if $. == 2" query/containerId_count.js
But I keep getting error :--
root#vm-test-001:~/mongosearch# distinct_array=`sed ':a;N;$!ba;s/\n/ /g' output/ontainerId_distinct.txt`
root#vm-test-001:~/mongosearch# declare -a arr=($distinct_array)
root#vm-test-001:~/mongosearch# batchsize=1
root#vm-test-001:~/mongosearch# IFS=,
root#vm-test-001:~/mongosearch# part=( "${arr[#]:i:batchsize}" )
root#vm-test-001:~/mongosearch# echo $part
"C:00000092666270:53882159774"
root#vm-test-001:~/mongosearch# perl -ni -e "print; print \"permissibleCars = [ ${part[*]} ]\n\" if $. == 2" query/containerId_count.js
Bareword found where operator expected at -e line 1, near ""permissibleCars = [ "C"
(Missing operator before C?)
String found where operator expected at -e line 1, near "53882159774" ]\n""
(Missing operator before " ]\n"?)
syntax error at -e line 1, near ""permissibleCars = [ "C"
Illegal octal digit '9' at -e line 1, at end of line
Execution of -e aborted due to compilation errors.
Can you help me with same ?
Regards
Try this:
export PARTS=${part[*]}
perl -lni -e 'print; print "permissibleCars = [".join(",",split/ /,$ENV{PARTS})."]" if $. == 2' query/containerId_count.js
And
In linux platform we should use single quote for one liner. From Perl black book see page number 19 and 20.

Is it possible get a particular argument in printf format in perl in command line?

It's needed to build a string foobar is not foo and not bar.
In printf format %$2s, "2" means a particular argument position.
But it doesn't work in perl:
$ perl -e "printf('%$1s$2s is not %$1s and not %$2s', 'foo', 'bar');"
%2 is not %1 and not %2
My env:
$ perl --version
This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi
(with 29 registered patches, see perl -V for more detail)
Your quoting is off.
perl -E 'say sprintf(q{%1$s%2$s is not %1$s and not %2$s}, "foo", "bar");'
foobar is not foo and not bar
You cannot use double quotes "" for the -e because your shell gets confused. You need single quotes there. But if you use double quotes for the printf pattern with the %1$s syntax, Perl will try to interpolate the $s, which doesn't work. So use a non-quoting q{} or escape the single quotes '' with \'. Or escape the $s.
If you turn on use strict and use warnings you'll see:
$ perl -E 'use strict; use warnings; say sprintf("%1$s%2$s is not %1$s and not %2$s", "foo", "bar");'
Global symbol "$s" requires explicit package name at -e line 1.
Global symbol "$s" requires explicit package name at -e line 1.
Global symbol "$s" requires explicit package name at -e line 1.
Global symbol "$s" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
That's with single quotes '' for -e and double quotes "" for the pattern.
$ perl -E "use strict; use warnings; say sprintf('%1$s%2$s is not %1$s and not %2$s', 'foo', 'bar');"
Invalid conversion in sprintf: "%1 " at -e line 1.
Invalid conversion in sprintf: "%2" at -e line 1.
%2 is not %1 and not %2
Now the shell tried to interpolate $s because of the double quotes "". So Perl never sees it. It sees the pattern as "%1 %2 is not %1 and not %2", which it cannot understand. (Note that the % will not get interpolated in double quoted strings in Perl).
This works for me on *nix:
perl -e "printf('%s%s is not %1\$s and not %2\$s', 'foo', 'bar');"
See the sprintf documentation, in particular the examples at the very end:
Here are some more examples; be aware that when using an explicit index, the $ may need escaping:
printf "%2\$d %d\n", 12, 34; # will print "34 12\n"
printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n"
printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n"
printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n"
printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n"
Let's have a look at the program you pass to perl:
$ printf '%s' "printf('%$1s$2s is not %$1s and not %$2s', 'foo', 'bar');"
printf('%ss is not %s and not %s', 'foo', 'bar');
As you can see, there is no $1 or $2 in your program because you improperly built your shell command. Just like Perl interpolates in double-quotes, so do sh and related shells. You should be using single quotes!
perl -e'printf("%\$1s\$2s is not %\$1s and not %\$2s\n", "foo", "bar");'
(I would have suggested switching from '' to q{} inside the Perl program so you wouldn't have to escape the dollar signs, but you need double-quotes for the \n you were missing anyway.)

Bareword found where operator expected at -e line 1, near "9A"

Why am I getting a syntax error?
% perl -ne 'if (/https://([-.0-9A-Za-z]+\.[-0-9A-Za-z]+)/) { print $1 ; }'
Bareword found where operator expected at -e line 1, near "9A"
(Missing operator before A?)
Bareword found where operator expected at -e line 1, near "9A"
(Missing operator before A?)
syntax error at -e line 1, near "9A"
syntax error at -e line 1, near ";}"
Execution of -e aborted due to compilation errors.
If the regex contains slashes, use a different character and the explicit m operator:
perl -ne 'if (m%https://([-.0-9A-Za-z]+\.[-0-9A-Za-z]+)%) { print $1 ; }'
Or:
perl -ne 'print $1 if m{https://([-.0-9A-Za-z]+\.[-0-9A-Za-z]+)}'
You need backslashes in front of the // after https:
perl -ne 'if (/https:\/\/([-.0-9A-Za-z]+\.[-0-9A-Za-z]+)/) { print $1 ; }'
Otherwise it thinks the regex is already over.

comparison of %2B in perl

I'm just trying to check if a string is equal to "%2B", and if it does I change it to "+".
The problem lies in comparison.
if ($lastItem == "%2B"){
$lastItem = "+";
}
When $lastItem is something completely different (like "hello"), it will still go into the statement. I've been wracking my brain and I just can't tell where I've gone wrong. Does %2B have some special meaning? I'm very new to perl.
Thanks
You need to use eq when comparing strings, or perl will try to convert the string to a number (which will be 0), and you will find such oddities as "a" == 0 to evaluate true. And when comparing two strings, you will of course effectively get if (0 == 0), which is the problem you are describing.
if ($lastItem eq "%2B") {
It is important to note that if you had used use warnings, this problem would have been easier to spot, as this one-liner will demonstrate:
$ perl -wE 'say "yes" if ("foo" == "bar")'
Argument "bar" isn't numeric in numeric eq (==) at -e line 1.
Argument "foo" isn't numeric in numeric eq (==) at -e line 1.
yes
I think you really want the following:
use URI::Escape qw( uri_unescape );
my $unescaped_last_item = uri_unescape($escaped_last_item);
URI::Escape
Please use use strict; use warnings;!
Another example where turning on use warnings would have made it simpler to work out what was wrong.
$ perl -Mwarnings -e'$l = "x"; if ($l == "%2B") { print "match\n" }'
Argument "%2B" isn't numeric in numeric eq (==) at -e line 1.
Argument "x" isn't numeric in numeric eq (==) at -e line 1.
match

Why does defined sdf return true in this Perl example?

I tried this example in Perl. Can someone explain why is it true?
if (defined sdf) { print "true"; }
It prints true.
sdf could be any name.
In addition, if there is sdf function defined and it returns 0, then it does not print anything.
print (sdf); does not print sdf string but
if (sdf eq "sdf")
{
print "true";
}
prints true.
The related question remains if sdf is a string. What is it not printed by print?
sdf is a bareword.
perl -Mstrict -e "print qq{defined\n} if defined sdf"
Bareword "sdf" not allowed while "strict subs" in use at -e line 1.
Execution of -e aborted due to compilation errors.
For more fun, try
perl -Mstrict -e "print sdf => qq{\n}"
See Strictly speaking about use strict:
The subs aspect of use strict disables the interpretation of ``bare words'' as text strings. By default, a Perl identifier (a sequence of letters, digits, and underscores, not starting with a digit unless it is completely numeric) that is not otherwise a built-in keyword or previously seen subroutine definition is treated as a quoted text string:
#daynames = (sun, mon, tue, wed, thu, fri, sat);
However, this is considered to be a dangerous practice, because obscure bugs may result:
#monthnames = (jan, feb, mar, apr, may, jun,
jul, aug, sep, oct, nov, dec);
Can you spot the bug? Yes, the 10th entry is not the string 'oct', but rather an invocation of the built-in oct() function, returning the numeric equivalent of the default $_ treated as an octal number.
Corrected: (thanks #ysth)
E:\Home> perl -we "print sdf"
Unquoted string "sdf" may clash with future reserved word at -e line 1.
Name "main::sdf" used only once: possible typo at -e line 1.
print() on unopened filehandle sdf at -e line 1.
If a bareword is supplied to print in the indirect object slot, it is taken as a filehandle to print to. Since no other arguments are supplied, print defaults to printing $_ to filehandle sdf. Since sdf has not been opened, it fails. If you run this without warnings, you do not see any output. Note also:
E:\Home> perl -MO=Deparse -e "print sdf"
print sdf $_;
as confirmation of this observation. Note also:
E:\Home> perl -e "print asdfg, sadjkfsh"
No comma allowed after filehandle at -e line 1.
E:\Home> perl -e "print asdfg => sadjkfsh"
asdfgsadjkfsh
The latter prints both strings because => automatically quotes strings on the LHS if they consist solely of 'word' characters, removing the filehandle interpretation of the first argument.
All of these examples show that using barewords leads to many surprises. You should use strict to avoid such cases.
This is a "bareword". If it is allowed, it has the value of "sdf", and is therefore not undefined.
The example isn't special:
telemachus ~ $ perl -e 'if (defined sdf) { print "True\n" };'
True
telemachus ~ $ perl -e 'if (defined abc) { print "True\n" };'
True
telemachus ~ $ perl -e 'if (defined ccc) { print "True\n" };'
True
telemachus ~ $ perl -e 'if (defined 8) { print "True\n" };'
True
None of those is equivalent to undef which is what defined checks for.
You might want to check out this article on truth in Perl: What is Truth?
defined returns true if the expression has a value other than the undefined value.
the defined function returns true unless the value passed in the argument is undefined. This is useful from distinguishing a variable containing 0 or "" from a variable that just winked into existence.