Bash – Output multiple files from a single grep

bashgrepshellzsh

I'm not very experienced in shell scripting, but I'm trying to understand how to grep for a pattern and for each file where there is a match write a file to disk that contains the matched line from grep. For example:

$ grep -E "MY PATTERN" myfile{1,3}

Then write out new files that contain the matching lines:

matches-myfile1
matches-myfile2
matches-myfile3

Is this possible? How can I do this? I'm looking for an answer is bash or zsh.

Best Answer

Bonsi has the right idea, but not the right approach (what should one do with filenames containing spaces or other whitespace characters, for example). Here is a way of doing it in bash:

for file in myfile{1,3}; do
    grep -E "MY PATTERN" < "$file" > "matches-$file"
done

If you did need to store the files you should account properly for word splitting, like so:

files=( myfile{1,3} )
for file in "${files[@]}"; do
    grep -E "MY PATTERN" < "$file" > "matches-$file"
done