2013-07-09 32 views
1

這裏是我的問題:Perl&Bash:找到正則表達式

我有一個perl腳本爲我搜索一些Linux文件。 文件名是這樣的:

shswitch_751471_126.108.216.254_13121 

問題是

13121 

是隨機增加的ID。 我試圖從今天早上開始搜索正確的正則表達式,但我無法找到它!請,你能幫忙嗎?

下面是我有:

#!/usr/bin/perl 
$dir = "/opt/exploit/dev/florian/scan-allied/working-dir/"; 
$adresse ="751471" ; 
$ip = "126.108.216.254"; 
$tab=`find $dir -type f -name \"$dir_$adresse_$ip_*\"`; 
print $tab; 

我甚至試過

$tab=`find $dir -type f -name \"$dir_$adresse_$ip_[0-9]{1}\"`; 

但Perl將不會聽我的話:(

+1

你忘了匹配 「shswitch」。在前面添加一個*,記住這不是*正則表達式匹配,而是一個glob,這是非常不同的。 –

+0

始終使用'use strict;使用警告;'! – ikegami

回答

2

改變這一行:

$tab=`find $dir -type f -name \"$dir_$adresse_$ip_*\"`; 

$tab=`find $dir -type f -name \"${dir}_${adresse}_${ip}_*\"`; 
+0

謝謝你們,是的,我忘了我已經在$迪爾,所以我刪除它。 現在我有: $ tab ='find $ dir -type f -name \「shswitch _ $ {adresse} _ $ {ip} _ * \」'; 效果很好!謝謝! –

+0

@ user2564494:不客氣。 – Toto

2

的問題是,你已經列入$dir文件名被傳遞到find

你也許想說:

$tab=`find $dir -type f -name \"shswitch_${adresse}_${ip}_*\"`; 
1

唔。如果您使用,那麼您並不需要致電find(1)!如果您使用File::Find模塊,則可以在沒有外部呼叫的情況下擁有更好的find。試試這樣:

#!/usr/bin/perl 

use strict; 
use warnings; 
use File::Find; 

my $dir = "/opt/exploit/dev/florian/scan-allied/working-dir/"; 
my $addresse ="751471" ; 
my $ip = "126.108.216.254"; 
my $re = "shswitch_${addresse}_${ip}_\d+"; 

sub wanted { 
    /^$re$/ and -f $_ and print "$_\n"; 
} 

find \&wanted, $dir; 

這將打印所有匹配的文件。

您可以使用find2perl實用工具將完整的find命令行轉換爲wanted函數!

對於

find2perl /opt/exploit/dev/florian/scan-allied/working-dir -type f -name \"shswitch_751471_126.108.216.254_${ip}_*\" 

下面的代碼給出:

#! /usr/bin/perl -w 
    eval 'exec /usr/bin/perl -S $0 ${1+"[email protected]"}' 
     if 0; #$running_under_some_shell 

use strict; 
use File::Find(); 

# Set the variable $File::Find::dont_use_nlink if you're using AFS, 
# since AFS cheats. 

# for the convenience of &wanted calls, including -eval statements: 
use vars qw/*name *dir *prune/; 
*name = *File::Find::name; 
*dir = *File::Find::dir; 
*prune = *File::Find::prune; 

sub wanted; 



# Traverse desired filesystems 
File::Find::find({wanted => \&wanted}, '/opt/exploit/dev/florian/scan-allied/working-dir'); 
exit; 


sub wanted { 
    my ($dev,$ino,$mode,$nlink,$uid,$gid); 

    (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) && 
    -f _ && 
    /^"shswitch_751471_126\.108\.216\.254__.*"\z/s 
    && print("$name\n"); 
}