Tuesday, January 4, 2022

[SOLVED] grep on multiple files, output to multiple files named after the original files

Issue

I have a folder with 64 items in it, numbered like this: 1-1, 1-2, 1-3, 1-4, 2-1 … What I want to do is grep the file 1-1 for a specific pattern, have the output saved to a new file named 1-1a, then move on to file 1-2, and so on. The pattern stays the same for all 64 files.

I tried variations with find and -exec grep 'pattern' "{} > {}a" but it seems like I can't use {} twice on one line and still have it interpreted as a variable. I'm also open to suggestions using awk or similar.


Solution

Should be easy with awk

awk '/pattern/{print > FILENAME "a"}' *

In order to use find, replace * with the results of a find command:

awk '/pattern/{print > FILENAME "a"}' $(find ...)`

... but do that only if the file names do not contain special characters (e.g. spaces) and the list doesn't grow too long. Use a loop in these cases.



Answered By - steffen