代码之家  ›  专栏  ›  技术社区  ›  Sharat Chandra

用于从目录中的文件列表中搜索的bash脚本

  •  1
  • Sharat Chandra  · 技术社区  · 16 年前

    $str 里面。

    我想写一个脚本,从中挑出包含字符串的行 $str

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

    例如,file1将搜索到的行转储到名为found1的文件中,file2将其转储到名为found2的文件中,等等。。。。

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

    3 回复  |  直到 16 年前
        1
  •  3
  •   Amirshk    16 年前

    grep -n "\$str" filename
    

    迭代文件:

    for file in *;
    do
        grep -n "\$str" $file >> "$file".result;
    done
    
        2
  •  3
  •   R Samuel Klatchko    16 年前
    for fname in file*; do
       grep ${str} ${fname} > ${fname/file/found}
    done
    

    魔法就在这里 ${fname/file/found} . 这将获取变量的值 ${fname}

    如果需要更复杂的转换,可以通过sed运行文件名转换。假设您想用“found”替换每次出现的“file”,您可以这样做:

    for fname in file*; do
        outfile=$(echo ${fname} | sed -e 's/file/found/g')
        grep ${str} ${fname} > ${outfile}
    done
    
        3
  •  1
  •   ghostdog74    16 年前

    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 
    
    推荐文章