[英]How can I use Awk inside a Perl script?
我在Perl腳本中使用以下代碼時遇到麻煩,請多多指教,如何更正語法?
# If I execute in bash, it's working just fine
bash$ whois google.com | egrep "\w+([._-]\w)*@\w+([._-]\w)*\.\w{2,4}" |awk ' {for (i=1;i<=NF;i++) {if ( $i ~ /[[:alpha:]]@[[:alpha:]]/ ) { print $i}}}'|head -n1
contact-admin@google.com
#-----------------------------------
#but this doesn't work
bash$ ./email.pl google.com
awk: {for (i=1;i<=NF;i++) {if ( ~ /[[:alpha:]]@[[:alpha:]]/ ) { print }}}
awk: ^ syntax error
# Here is my script
bash$ cat email.pl
####\#!/usr/bin/perl
$input = lc shift @ARGV;
$host = $input;
my $email = `whois $host | egrep "\w+([._-]\w)*@\w+([._-]\w)*\.\w{2,4}" |awk ' {for (i=1;i<=NF;i++) {if ( $i ~ /[[:alpha:]]@[[:alpha:]]/ ) { print $i}}}'|head -1`;
print my $email;
bash$
如果要在Perl中進行編碼,請使用諸如Net :: Whois之類的模塊。 在CPAN中搜索有關網絡的更多此類模塊。 如果您只想使用不帶模塊的Perl,可以嘗試一下(請注意,由於Perl擁有自己的grepping和字符串操作工具,因此您不必再使用egrep / awk)
open(WHOIS, "whois google.com |") || die "can't fork whois: $!";
while (<WHOIS>) {
print "--> $_\n"; # do something to with regex to get your email address
}
close(WHOISE) || die "can't close whois: $!";
在Perl中使用awk的最簡單(盡管不是最流暢)的方法是a2p
。
echo 'your awk script' | a2p
正如其他人所提到的,反引號會插值,因此它會在$
上跳閘。 您可以將它們全部轉義,或者可以使用單引號,如下所示:
open my $pipe, "-|", q[whois google.com | egrep ... |head -n1];
my $result = join "", <$pipe>;
close $pipe;
這利用了open
的能力來打開管道。 -|
指示文件句柄$pipe
應該附加到命令的輸出。 這里的主要優點是您可以選擇引用類型, q[]
等效於單引號,並且沒有插值,因此您不必轉義。
但是,天哪,將awk腳本粘貼到Perl中有點愚蠢而脆弱。 使用Net :: Whois之類的模塊,或者在Perl中進行whois抓取,可能利用Email :: Find之類的優勢,或者僅將其編寫為bash腳本。 就目前而言,您的Perl腳本在Perl中的作用不大。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.