tags:

views:

143

answers:

4

There are around 20 files in a directory . Each file has the string $str inside it.

I want to write a script that picks out that row containing the string $str and dump into a file .

Each file should dump the searched row into a different file .

For example file1 dumps searched row to file called found1 and file2 dumps it to file called found2 etc....

Can anyone please guide me regarding this ?

I'm particularly finding it difficult to include the file name in the grep command.

I can't go on to include 20 grep commands.

+3  A: 

Printing the rows with numbers:

grep -n "\$str" filename

Iterating files:

for file in *;
do
    grep -n "\$str" $file >> "$file".result;
done
Am
@Am: that's fine! +1
RageZ
@Ragez, i tested and it failed, now it's ok :)
Am
-1 for using (ls). --> for file in * will do.
ghostdog74
@ghostdog74: tnx, something new everyday
Am
@all thank you :)
Sharat Chandra
+3  A: 
for fname in file*; do
   grep ${str} ${fname} > ${fname/file/found}
done

The magic is in ${fname/file/found}. This takes the value of the variable ${fname} but substitutes the first occurence of 'file' with 'found'.

If you need more complex transformation, you can run the the filename through sed. Let's say you want to substitute every occurence of 'file' with 'found' you could do this:

for fname in file*; do
    outfile=$(echo ${fname} | sed -e 's/file/found/g')
    grep ${str} ${fname} > ${outfile}
done
R Samuel Klatchko
no need to use sed. with the shell, just do ${fname//file/found}
ghostdog74
+1  A: 

use gawk

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

or entirely with shell

#!/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
ghostdog74
A: 

R Samuel Klatchko solution seems the most sane; I would quote those variable to be on the safe side though.

Derek Schrock