[英]Grep from within perl script
關於如何從perl腳本中聲明grep,我有些困惑。 我想做的是讓我的perl腳本執行以下命令:
cat config.ini | grep -v "^#" | grep -v "^$"
通常,此表達式將清除/過濾所有以#和$開頭的條目,並打印配置的變量。
但是我不知道如何聲明它。 我使用了下一個表達式,但是當我要介紹grep#或$時,它失敗了
system("(cat config.ini| grep ........);
有什么建議嗎?
cat config.ini | grep -v "^#" | grep -v "^$"
是一種糟糕的寫作方式
grep -v "^[#$]" config.ini
產生琴弦
grep -v "^[#$]" config.ini
您可以使用字符串文字
'grep -v "^[#$]" config.ini'
所以
system('grep -v "^[#$]" config.ini');
die("Killed by signal ".($? & 0x7F)."\n") if $? & 0x7F;
die("Exited with error ".($? >> 8)."\n") if $? >> 8;
system('grep -v "^[#$]" config.ini');
是短的
system('/bin/sh', '-c', 'grep -v "^[#$]" config.ini');
但是我們不需要外殼程序,因此可以使用以下內容代替:
system('grep', '-v', '^[#$]', 'config.ini');
die("Killed by signal ".($? & 0x7F)."\n") if $? & 0x7F;
die("Exited with error ".($? >> 8)."\n") if $? >> 8;
但是在Perl中這樣做會更清潔,更強大。
open(my $fh, '<', 'config.ini')
or die($!);
while (<$fh>) {
print if !/^[#$]/;
}
如果要從Perl程序內部對grep
進行外部調用,那么您做錯了。 grep
無法做到Perl無法為您完成的工作。
while (<$input_filehandle>) {
next if /^[#$]/; # Skip comment lines or empty lines.
# Do something with your data, which is in $_
}
更新:對此進行進一步的思考,我想我會寫得有些不同。
while (<$input_filehandle>) {
# Split on comment character - this allows comments to start
# anywhere on the line.
my ($line, $comment) = split /#/, $_, 2;
# Check for non-whitespace characters in the remaining input.
next unless $line =~ /\S/;
# Do something with your data, which is in $_
}
print if !(/^#/|/^$/);
我確實嘗試過使用建議的表達式,但效果不如該表達式,有沒有辦法減少它或以更好的方式編寫ir?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.