| « The first | New arrival » |
Fri, Sep 24, 2010
![[Icon]](rsc/img/chain_link.gif)
Another of those little command-line things I've found incredibly useful lately: The backtick. It looks like a slanty apostrophe, and on a GB keyboard it's in the top-left corner: `
What this does it make it really simple to turn the output of one command into the input of another.
"So what?" you might say, "That's what pipes do."
But they don't!
Suppose that you want to get a list of files containing a certain string. Obviously, you'd use grep:
grep 'string' directory/ -r
This will look in every file in the directory of your choice and find you every single one that has 'string' in it.
Now suppose you want to figure out which was the most recently-edited of those files? Try doing that with a pipe :P
With backticks, it's easy: First, you need to get just the list of files, not their contents. This is easy with the -l switch:
grep 'string' directory/ -rl
That gives you the files you want. Now you just pass those files to ls
ls `grep 'string' directory/ -rl`
This is telling ls to list all the files returned by grep. However, it's still not doing what we want, because we need to pass ls a couple more options:
ls `grep 'string' directory/ -rl` -lt
Done. A list of files containing 'string' in chronological order of edits.
All courtesy of the backtick turning the output of one file into another.
Another example would be, what if you wanted all files which contained both 'string1' and 'string2' - a single grep can't help here. But two greps with backticks can:
grep 'string2' `grep 'string1' directory -lr` -l
This finds all files with string1 in, then passes those filenames to a second grep that then checks to see if those files also have string2.
Pretty cool, huh? :o)
![[Links]](http://geekblog.oneandoneis2.org/skins/112/rsc/img/chain_link.gif)
I'm in the Perl newsletter again. I should try and write about some other language...
21/05/12
Facebook Syndication Error
22/05/12
![]()
I last listened to:
Johann Pachelbel - Canon in D major
Most recent photo:
js.js