Find files that have YAML frontmatter

July 7, 2015 blogging YAML bash fish shell shell scripting

Here’s a bash one liner that will find all files in the current directory that have YAML front matter:

find . -exec sh -c 'if (head -n 1 "{}" | grep -- --- >/dev/null); then echo "{}"; fi' \;

If you need files that don’t have front matter, grep -v will do the trick:

find . -exec sh -c 'if (head -n 1 "{}" | grep -v -- --- >/dev/null); then echo "{}"; fi' \;

If you need a different directory, or files of a specific type, find has lots of flexibility:

find ~/Dropbox/blog -iname '*.md' -exec sh -c 'if (head -n 1 "{}" | grep -v -- --- >/dev/null); then echo "{}"; fi' \;

You can also use for loops, for example in syntax-light fish shell:

for file in source/articles/*.txt
    if head -n 1 $file | grep -- --- >/dev/null
        echo $file
    end
end

Buy Me a Coffee at ko-fi.com