The *nix Rube Goldberg machine – shift

Learn your shell!

If you have been following along, I love bash and use it all the TIME! I’ll go as far as to say its the greatest thing I’ve learned in my entire career.

In my last bash post I talked about how you can write functions to alias complex tasks. One of the most common things you do in bash is grep through files.

~/lecode>find -name *.js | xargs grep "fn\.somePlugin"

I can’t tell you how many times I’ve typed find -name …. | xargs grep ….

“LUL WTF, noob haven’t you ever heard of ack?”

“Of course I have, but you have to install that shit and I’m lazy… So shut up troll”

So… finally I decided to save myself some keystrokes and make a function.

~/lecode>function ff() {
arg1=$1
arg2=$2
shift 2
find -name $arg1 -type f -print0 | xargs -0 grep $arg2 $@
}

shift is really cool, it lets me capture off the first two arguments

arg1=$1
arg2=$2

then call shift 2 which will remove the first two arguments from the `splat` (`$@`) so that I can pass those off to grep. This saves me a bunch of keystrokes when working with grep.

ff *.js "fn\.somePlugin"

That will search all js files for that regex.

By shifting the splat I can give extra flags to grep like -l (only the file name)

ff *.js "fn\.somePlugin" -l

or -h for just the match

ff *.js "fn\.somePlugin" -h

Don’t herp it, just derp it

-Ryan

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Ryan Rauh

My name is Ryan Rauh and I like shiny things. If I've seen it on twitter more the twice most likely I've looked at it or tried it. I really like memes and other silly and seemingly useless things out on the internet. I blog about things *I* think are cool and interesting, I hope you will find them cool and interesting too.
This entry was posted in Shell, Uncategorized and tagged . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://DhilipSiva.com/ DhilipSiva Bijju

    Wow, thank you. I am a newbie, I didnt know that one could define functions on terminal. Nice post. Saves me lot a of time.

  • Roman Kvasov
  • http://twitter.com/vsevolod Vsevolod Parfenov

    Also you can use (works in git bash) something like
    grep -r “langref” Pages/de/*[^0-9].cs

    For your sample
    grep -r “fn.somePlugin” *.js