2016-05-15 42 views
-2

我有一個文件夾結構等:grep的文件夾名和子文件內容

debug/$domain/info.txt

在調試是像200個域

,我想到grep的info.txt文件的每個域的特定內容 所以我想記下域名+我需要grep的info.txt的內容部分。

我嘗試了很多東西,但我失敗了。

for D in $(find . -type d); do 
    grep xxx D/info.txt 
done 

如果您有任何想法如何做,請讓我知道。

謝謝:)

+0

與內容info.txt的一部分,建立一個正則表達式... – Jahid

+2

歡迎SO ,請展示您的編碼工作。 – Cyrus

+0

內容的正則表達式已完成。只是僞裝的東西。 – user5293028

回答

0

有您的正則表達式部分(查找內容)已經完成,嘗試這樣的事情:

while IFS= read -r -d $'\0'; do 
    domain="${$REPLY##*/}" 
    content="$(grep -o xxx $REPLY/info.txt)" 
    echo "$domain: $content" >> log.txt 
done < <(find . -type d -print0) 

或使用for循環的嘗試:

for D in $(find . -type d); do 
    content="$(grep -o xxx D/info.txt)" 
    domain="$D##*/" 
    echo "$domain: $content" >>log.txt 
done 

雖然請記住,這個for循環是而不是空白區域安全,但對於這種特殊情況無關緊要。

0

下面的腳本是這樣做的另一種方式:

find /path/to/search/for -type f -name "*info.txt" -print0 | while read -r -d '' line 
do 
domain=$(sed 's/^.*debug\/\(.*\)\/info.txt/\1/' <<<"$line") 
content=$(grep "text_to_grab" "$line") 
printf "%s : %s\n" "$domain" "$content" >>logfile 
done 
0

因爲在您添加標記的perl你的問題,我公司提供使用Perl的解決方案。

use strict; 
use diagnostics; 

my $search_for = qr{abc}; #string to search for 

print search_info_files($search_for); 

sub search_info_files { 
    my $rex  = shift; 
    my $file_name = 'info.txt'; 

    chdir 'debug' or die "Unable to chdir to debug: $!\n"; 

    my @domains = glob("*"); 

    foreach my $domain (@domains) { 
     next unless -d $domain; 
     next unless -f $domain . '/' . $file_name; 

     open my $fh, '<', $domain . '/' . $file_name 
      or die "Unable to open $domain/$file_name: $!\n"; 

     while (<$fh>) { 
     chomp(my $line = $_); 
      next unless $line =~ $rex; 
      print "'$domain' matches (line#: $.): $line.\n"; 
     } 

     close $fh; 

    } 
} 
__END__ 
Sample output: 
'a' matches (line#: 1): As easy as abc. 
'b' matches (line#: 2): abcde. 
'c' matches (line#: 1): abcde. 
'c' matches (line#: 3): abcde. 
'c' matches (line#: 5): Sometimes more than one line contains abc. 
'd' matches (line#: 1): abcde. 
'd' matches (line#: 3): abcde. 
'e' matches (line#: 1): abcde. 

例如調試/ C/info.txt包含:需要

abcde 
fghij 
abcde 
fffff 
Sometimes more than one line contains abc 
相關問題