From f6577d5018615b04172aee8770980b72a98bb1df Mon Sep 17 00:00:00 2001 From: Thomas Date: Mon, 11 Mar 2024 21:12:57 +0000 Subject: [PATCH] blog: Code Snippet: Count number of files with an extention --- .../blog/2024-03-11-code-snippet-tree-grep.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/content/blog/2024-03-11-code-snippet-tree-grep.md diff --git a/src/content/blog/2024-03-11-code-snippet-tree-grep.md b/src/content/blog/2024-03-11-code-snippet-tree-grep.md new file mode 100644 index 0000000..6b934d1 --- /dev/null +++ b/src/content/blog/2024-03-11-code-snippet-tree-grep.md @@ -0,0 +1,29 @@ +--- +title: 'Code Snippet: Count the number of files with an extention ' +date: 2024-03-11T21:09:52.651Z +slug: 2024-03-11-code-snippet-tree-grep +author: Thomas Wilson + +--- +I wanted to know how many files that ended in either `.test.ts` or `.test.js` in a directory, came up with this guy: + +```sh +tree --noreport --gitignore -i | grep -c -E '\.test\.(js|ts)' +``` + +## Tree + +[tree](https://formulae.brew.sh/formula/tree) is a tool for listing out the contents of a directory in a tree-style format. + +- `--noreport` Removes a summary line at the bottom ("10 directories, 35 files") +- `--gitignore` Looks for a `.gitignore` file and excludes those directories, useful for those pesky `node_modules` directories +- `-i` Removes the whitespace and indent (makes it better input for regex) + +## Grep + +Grep is a tool for searching text against a regex. + +We pass in the input from tree into Regex, and only look for files that match a pattern + +- `-c` for "count", i.e. just tell me how many matches you found +- `-E`for extended regex, it makes the `(js|ts)` fragment work