Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

grep on multiple files, output to multiple files named after the original files

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading