2009-06-02 55 views
-1

我正試圖讀取由數百個文件組成的目錄。對於目錄中的每個文件,我應該訪問(編輯)另一個文件,並通過'/ home/test/test_these_files'目錄中的文件名'information ='替換該文件中的特定字符串'information = filename'。接着執行文件'/home/test/controlfile.txt'。我寫了下面的腳本,並嘗試將文件的名稱作爲數組傳遞以替換(字符串中的文件名)。我知道這不會工作,但我不知道什麼會工作。有什麼建議麼?僅供參考:程序不顯示任何編譯錯誤。如何在需要替換的字符串中輸入不同的文件名?

#!use/bin/perl 
use strict; 
use warnings; 

my $find = 'information=filename'; 

opendir (DIR, "/home/test/test_these_files") || die "can't open directory"; 
my @files = grep(/.aa/, readdir(DIR)); 
print @files; 
print "\n"; 
closedir(DIR); 

foreach (@files) { 
    my $replace = 'information=<@files>'; # want to replace with 'information=<filenames> 
    #filenames are names of files present in the '/home/test/test_these_file' directory 
    open (FILE, '/home/test/controlfile.txt') || die "cant open file \n"; 
    my @body = <FILE>; 
    print @body; 
    open (OUT, '>/home/test/controlfile.txt') || die "can't create file \n"; 
    foreach $_ (@body) { 
     (s/$find/$replace/g); 
     print OUT "$_"; 
    } 
    'perl /home/test/controlfile.txt'; 
    close(FILE); 
    close(OUT); 
} 
exit; 
+0

縮進是你的朋友。什麼是''perl /home/test/controlfile.txt';`應該這樣做? $ replace被設置錯誤。 – Schwern 2009-06-03 04:08:46

回答

0

你的主要錯誤可能是在你的家當:中

#!/usr/bin/perl 

代替

#!use/bin/perl 

此外,你可以改一下你的問題。真的很難理解你想說什麼。

- 編輯

我想我明白你的問題,你需要創建一個文件,該文件的索引存在於特定目錄中的所有文件。

需要考慮的事項1)您是否正在尋找一個名爲任何字符,然後AA或任何與.aa 2)的擴展名的文件是否需要索引文件不存在

#!/usr/bin/perl 

use strict; 

$files_dir = '/home/test/test_these_files'; 
#$file_ext = '.*\.aa'; # Get files with extension of .aa 
$file_ext = '.aa'; # Get files with any character followed by 'aa' 
$index_file = '/home/test/controlfile.txt'; 

# Scan the directory 
opendir(DIR, $files_dir) || die "can't open directory"; 
# Get "file.aa" or "{char}aa" ? 
my @files = grep($file_ext, readdir(DIR)); 
closedir(DIR); 

$index_string = ''; 
foreach $file (@files) { 
    $index_string .= $file . ' '; 
} 
chomp($index_string); 

# If needed prepend previous index 
# .... 

$index_string = 'information=' . $index_string; 
open(FILE, '>', $index_file) || die "cant open file \n"; 
    print FILE, $index_string; 
close(FILE); 

嘗試那個。祝你好運。

+0

謝謝!有效。現在已經停留了很長一段時間了。 – shubster 2009-06-03 14:57:04

1

它根本不清楚你想做什麼,但是通過閱讀和寫入相同的文件和一些粗略的語法,它幾乎看起來像這就是你想要做的。儘管SEARCH和REPLACE的來源不明確。如果那在控制文件裏面有一個文件名,那麼這很容易收集。

for FILE in `cat controlfile` 
do 
    perl -i -e 's/SEARCH/REPLACE/' ${FILE} 
done 
相關問題