2009-11-20 68 views
1

目录中有大约20个文件。每个文件都有内部的字符串$str用于从目录中的文件列表中搜索的bash脚本

我想编写一个脚本来挑选包含字符串$str的行并将其转储到文件中。

每个文件都应该将搜索到的行转储到不同的文件中。

例如file1中转储检索行文件调用,招致和file2文件备份到硬盘称为found2等....

任何人都可以请指导我对此?

我特别发现很难在grep命令中包含文件名。

我不能继续包括20个grep命令。

回答

3

打印与数字行:

grep -n "\$str" filename 

遍历文件:

for file in *; 
do 
    grep -n "\$str" $file >> "$file".result; 
done 
+0

@Am:没关系! +1 – RageZ 2009-11-20 06:23:03

+0

@Ragez,我测试过,失败了,现在没关系:) – Amirshk 2009-11-20 06:29:16

+1

-1使用(ls)。 - >为文件在*将做。 – ghostdog74 2009-11-20 06:32:11

3
for fname in file*; do 
    grep ${str} ${fname} > ${fname/file/found} 
done 

神奇的是在${fname/file/found}。这取得变量${fname}的值,但用'found'代替'file'的第一次出现。

如果您需要更复杂的转换,您可以通过sed运行文件名。比方说,你想替换用“发现”你可以做到这一点“文件”的每一次出现:

for fname in file*; do 
    outfile=$(echo ${fname} | sed -e 's/file/found/g') 
    grep ${str} ${fname} > ${outfile} 
done 
+0

不需要使用sed。用shell,只需要$ {fname // file/found} – ghostdog74 2009-11-20 07:09:53

1

使用呆子

str="mypattern" 
gawk -v str=$str 'FNR==1{close("found_"d);d++}$0~str{print $0>"found_"d}' file* 

或完全与外壳

#!/bin/bash 
d=0 
str="mystring" 
for files in file file1 file2 
do 
    d=$((d+1)) 
    f=0 
    while read -r line 
    do 
     case "$line" in 
     *$str*) echo $line >> "found_$d" ; f=1;;  
     esac 
    done < ${files} 
    [ "$f" -eq 0 ] && d=$((d-1)) 
done