Wednesday, October 26, 2022

[SOLVED] How do I get all files with .md extension, in all subdirectories, that contain a phrase?

Issue

I have a parent folder named 'dev', and inside it are all my project folders. The ReadMe files of these projects contain the app type "type: game", for example. What I would like to do is to:

  1. search through all subdirectories of the dev folder to find all the files with *.md" extension

  2. then return the names of those directories which contain a .md files with containing the phrase "game"

I've tried piping find into grep like so:

find -type f -name "*.md" | grep -ril "type: game"

But it just returns the names of files from all subdirectories which contain the phrase "game" in any file.


Solution

find . -type f -name "*.md" -print0 | xargs -0 grep -il "type: game" | sed -e 's/[^\/]*$//'

This finds any files in the current directory and sub-directories with names ending with .md, then greps for files containing the string. We then use sed to trim the filename leaving only the directories containing a file ending in .md with the "type: game" inside.



Answered By - James Risner
Answer Checked By - Pedro (WPSolving Volunteer)