4

I often need to run some Perl one-liners for fast data manipulations, like

some_command | perl -lne 'print if /abc/'

Reading from a pipe, I don't need a loop around the command arg filenames. How can I achieve the next?

some_command | perl -lne 'print if /$ARGV[0]/' abc

This gives the error:

Can't open abc: No such file or directory.

I understand that the '-n' does the

while(<>) {.... }

around my program, and the <> takes args as filenames, but doing the next every time is a bit impractical

#/bin/sh
while read line
do
   some_command | perl -lne 'BEGIN{$val=shift @ARGV} print if /$val/' "$line"
done

Is there some better way to get "inside" the Perl ONE-LINER command line arguments without getting them interpreted as filenames?

4

3 回答 3

5

也相当短:

... | expr=abc perl -lne 'print if /$ENV{expr}/'

bashshell 中工作,但可能不适用于其他 shell。

于 2013-05-13T15:01:42.237 回答
3

一些解决方案:

perl -e'while (<STDIN>) { print if /$ARGV[0]/ }' pat

perl -e'$p = shift; while (<>) { print if /$p/ }' pat

perl -e'$p = shift; print grep /$p/, <>' pat

perl -ne'BEGIN { $p = shift } print if /$p/' pat

perl -sne'print if /$p/' -- -p=pat

PAT=pat perl -ne'print if /$ENV{PAT}/'

当然,创建一个 ORing 或所有模式的模式可能比为每个模式执行相同的命令更有意义。

于 2013-05-13T20:58:49.047 回答
2

这取决于您认为阅读的内容会是什么,但您可以玩:

#/bin/sh
while read line
do
   some_command | perl -lne "print if /$line/"
done

显然,如果$line可能包含斜线,这不会飞。然后,AFAIK,你被 BEGIN 块公式困住了。

于 2013-05-13T14:52:54.447 回答