Grep'in with the Best of `Em 🫣
The grep command 💾
When you want or need to look through all the files grep is tops 🎩. Particularly for a DevSecOps engineer
when we're jumping in and out of different code bases all day and trying to find where and if a particular
error, string, or variable is used. Grep can help get us there. Here is a baseline grep on my codebase:
1 2 3 | |
This is a search for the string "requests" in the requiremnts.txt file, and it reveals that the string
appears in two lines of the file. That's nice, but we can do better.
grep -n 🚀
Adding the -n flag allows us to reveal the line number that the result occurs on:
the output of ls -a on the same gspc.digital directory:
1 2 3 | |
Now we know the string occurs in the file twice and what line numbers to look on; woot 🤩, now we are getting somewhere.
grep -i 🙈
Using the -i flag you we can ignore case in the search:
1 2 3 | |
So, when and, if we're not sure of the case of the string we are looking for -i is our friend ✅.
Recursive grep -r 🔄
When we want to search through all the files in a directory we can use the -r flag. Say we want to
find all the places the requests library is used in our codebase.
1 2 3 4 5 6 7 8 9 10 11 12 | |
This is good, but this particular grep produced 3899 results. Some from the .venv directory, tests directory, and some binary files.
If we're trying to troubleshoot a codebase and suspect a problem with requests, but not sure where to start, we likely don't care
about .venv, .git, or binary files amongst others. What to do 🤔, what to do? ⁉️
Enter the --exclude-dir flag ⎆
Using --exclude-dir we can eliminate some of the extraneous results (as far as troubleshooting is concerned).
1 2 3 4 5 6 7 8 | |
Excluding the .venv directory got the results down to 21 lines of code. Nice one. Perhaps we decide that
a that the static markdown files aren't relevant to the troubleshooting we can omit those too:
1 2 3 | |
Now just 2 results to deal with. 🎉
Kitchen Sink grep -Erin <stuff\.thing> --exclude-dir=".venv" 🚰
Putting it all together we can combine flags (we've been doing that all along in this post 📜) and throw in
the -E flag to use regular expressions. This can be useful when we're looking for a string that's part of a larger
sequence.
Conclusion 🎁
Grep is an everyday goto. For DevSecOps I'd argue essential. It's true that you can search a codebase
via your editor in similar ways, but grep works locally, on bare metal, and in the cloud ☁️.
Be sure to check:
1 | |
for full details and to take it to the next level. 🚀 Let me know if you have any grep tips or tricks