Last Updated: February 25, 2016
·
633
· ryepdx

How to search for strings on uncommented Python lines using a Bash function

Recently I found myself wanting an easy way to grep for strings in uncommented lines in my Python files. I was tired of re-typing the same --excludes and regexes over and over. I'd already been using alias for a while to shorten commands I found myself using a lot, but I needed a way to plug a string into the regex at runtime, and I found myself hindered by the fact that I couldn't reference arguments to the alias in its definition. I remembered that Bash lets you define new functions right on the command line, so I ended up writing a Bash function:

function pygrep () { grep -r --exclude="*.pyc" --exclude="*.swp" ^[^#]*$1.* ${@:2}; }

Usage:

pygrep "search_string_here" optional_list_of_files_and_directories

In the function definition above, $1 stands for the first argument to the function. $2 would, of course, stand for the second, $3 would stand for the third, and so on. $@ is an array of all of the arguments to the function. In this example, I'm grabbing all its elements from the second element on. If I wanted to just get the two arguments following the first one, I could have instead referenced ${@:2:2}. The number after the first colon is the starting index (inclusive), and the number after the second colon is the number of elements to grab.

If you find a function particularly useful (as I've found the one above), don't forget to add it to your ~/.bashrc file so you can continue using it in your next Bash session.