Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass both variables and files to a perl -p -e command

I have a command line written in perl that executes in Solaris (maybe this is irrelevant as it is UNIX-like) which inserts a "wait" string every 6 lines

perl -pe 'print "wait\n" if ($. % 6 == 0);' file

However, I want to replace that 6 by a parameter (ARGV[0]), resulting in something like this:

perl -pe 'print "wait\n" if ($. % ARGV[0] == 0);' file 6

It goes well, giving me the right output, until it finishes reading the file and treats "6" as the next file (even when it understood it as ARGV[0] before).

Is there any way to use the -p option and specify which parameters are files and which ones are not?


Edited: I thought there was a problem with using the -f option but as @ThisSuitIsBlackNot pointed out, I was using it wrongly.

like image 376
Gabriel Avatar asked Oct 18 '25 05:10

Gabriel


1 Answers

-p, as a superset of -n, wraps the code with a while (<>) { } loop, which reads from the files named on the command line. You need to extract the argument before entering the loop.

perl -e'$n = shift; while (<>) { print "wait\n" if $. % $n == 0; print }' 6 file

or

perl -pe'BEGIN { $n = shift }  print "wait\n" if $. % $n == 0' 6 file

Alternatively, you could also use an env var.

N=6 perl -pe'print "wait\n" if $. % $ENV{N} == 0' file
like image 122
ikegami Avatar answered Oct 20 '25 10:10

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!