vagrant
vagrant

Reputation: 81

Passing bash variable to perl one-liners - insights required

I am fairly new to Perl and I have been toying with one-liners to get some file operations done. I am using Perl to print segment between defined by line numbers which are obtained from another file. My current issue is as follows:

export var=10 ; perl -ne 'print $_ if $. == $ENV{var}' filename.txt 

prints line number 10, but if i want to print from line 10 to the end of file, i tried

export var=10 ; perl -ne 'print if $ENV{var} .. -1' filename.txt 

--fails. The output generated prints the whole file. Additionally, the following works,

export var=10 ; perl -ne 'print if $. >= $ENV{var} $$ $. <= $ENV{var}+5 ' filename.txt

But since i am dealing with a variable file length after the required line, this is not a viable solution.

Upvotes: 2

Views: 2897

Answers (3)

Tiago Lopo
Tiago Lopo

Reputation: 7969

You don't need to use Environmental variables:

var=10; echo "$(seq 20 35)" | perl -lne 'print if $. >= '"$var"';'
29
30
31
32
33
34
35

Take a look at the way I escaped $var

Using flip-flop:

var=10; echo "$(seq 20 35)" | perl -lne 'print if $.== '"$var"' .. -1;'
29
30
31
32
33
34
35

Upvotes: 2

mpapec
mpapec

Reputation: 50677

Perl flip-flop operator has some of his own warts (like is my variable line number or boolean?), so when in doubt do explicit comparison to $. line number.

export var=10 ; perl -ne 'print if $.== $ENV{var} .. -1' filename.txt 

Upvotes: 3

Nathan Campos
Nathan Campos

Reputation: 29507

From line 10 to the end of the file:

export var=10 ; perl -ne 'print $_ if $. > $ENV{var}' filename.txt

If you want it to include line 10:

export var=10 ; perl -ne 'print $_ if $. >= $ENV{var}' filename.txt

Upvotes: 1

Related Questions