MDN Blog: How to search code using grep

A big part of web development extends beyond the usual suspects of HTML, CSS, JavaScript, and HTTP. You need to glue these building blocks together, and for that, you need to be able to use tools, systems, and other fundamentals.

Aside from soft skills, understanding how files and file systems work, using shell scripting languages, working with IDEs, and managing the actual code are developer essentials.

I think that search is one of the most important skills when it comes to working with code. I make searches using grep many times a day to look for all kinds of patterns in code and documentation. If I find a typo in a document on MDN, I'll use grep to search all of MDN Web Docs to see if there are others like it or if it's copy-pasted elsewhere. For code, I'll look where variables are defined in a project, error messages in logs, patterns that are deprecated or need to be refactored, and so on.

# find "the the " repeated word typo
grep -r "the the " files
# path/to/index.md: and upper limit or the the keyword `auto`.

# find legacy rgba() CSS function, ignore node_modules
grep -r --exclude-dir=node_modules "rgba(" ./
# ./files/path/to/index.md:  background: rgba(0, 0, 0, 0.3);

# Count macros like {{jsxref("RegExp")}}
grep -rEoh "{{.+?}}" ./files/**/*.md | sort | uniq -ic
#  90 {{jsxref("RegExp")}}

If you want to learn how to use grep, I wrote a post for the MDN Blog that will get you started with interesting and fun examples to try. Check it out if you'd like to read about:

  • what grep is and how to use it
  • piping commands into grep
  • some real-world timings to show how fast it is compared to alternatives
  • why I think learning grep will give you a serious skills and productivity boost
# time how long it takes to grep for a pattern and
# perform a line count on the output
time grep -r "\`\`\`plain" files/en-us/web/ | wc -l
     252
grep -r  0.43s user 0.29s system 99% cpu 0.730 total
wc -l  0.00s user 0.00s system 0% cpu 0.729 total

If you liked the post, you should also see the JavaScript regular expression updates. Let me know what you think about the MDN blog post and if you use grep for something fun. Leave a comment below or get in touch on Mastodon.

Happy /(grep|hack)ing)/ :mag: