I want to search for a string and get the full line from a text file through Perl scripting.
So the text file will be like the following.
data-key-1,col-1.1,col-1.2
data-key-2,col-2.1,col-2.2
data-key-3,col-3.1,col-3.2
Here I want to apply data-key-1
as the search string and get the full line into a Perl variable.
Here I want the exact replacement of grep "data-key-1" data.csv
in the shell.
Some syntax like the following worked while running in the console.
perl -wln -e 'print if /\bAPPLE\b/' your_file
But how can I place it in a script? With the perl
keyword we can't put it into a script. Is there a way to avoid the loops?
Best Answer
If you'd know the command line options you are giving for your one-liner, you'd know exactly what to write inside your
perl
script. When you read a file, you need a loop. Choice of loop can yield different results performance wise. Usingfor
loop to read a while is more expensive than using awhile
loop to read a file.Your one-liner:
is basically saying:
-w
: Use warnings-l
: Chomp the newline character from each line before processing and place it back during printing.-n
: Create an implicitwhile(<>) { ... }
loop to perform an action on each line-e
: Tellperl
interpreter to execute the code that follows it.print if /\bAPPLE\b/
to print entire line if line contains the wordAPPLE
.So to use the above inside a
perl
script, you'd do:chomp
is not really required here because you are not doing anything with the line other then checking for an existence of a word.