March 25, 2019

The Linux CLI for Beginners, or, Fear Not the Linux Command Line! - page 3

Please Meet the Linux Terminal

  • December 12, 2008
  • By Akkana Peck

"grep" is kind of a nasty name -- there's some disagreement on what it stands for, including "Globally search for Regular Expressions and Print" and "General Regular Expression Parser". But it's an incredibly useful program that prints just the lines matching a particular pattern.

For instance, to combine the squirrel search and the tiger search, you just pipe one search through grep, passing grep the second pattern:

$ locate squirrel | grep tiger

locate squirrel found all those squirrel images, then grep searched through all of them to find any that also had "tiger" in the name. Now I know exactly where the file is.

Counting lines

Pipelines aren't limited to just two commands, though. For instance, remember that long list of files with cat in the name? I know there's a program called "cat"; suppose I want to know how many of those other files with "cat" in the name are programs.

Programs are usually located in /usr/bin, but sometimes they're in /bin or some other place. But they usually have "bin" in the name somewhere. So if I take all the files that have both "cat" and "bin" in the name:

$ locate cat | grep bin
I can then find out how many lines there were, by using the useful wc (word count) program:
$ locate cat | grep bin | wc -l

wc -l says to count the number of lines (that's ell for "lines", not a one) -- if you omit the -l part, it prints lines, words and characters.

On my system I have 34 programs with cat in the name. How many do you have?

Akkana Peck is a freelance programmer whose credits include a tour as a Mozilla developer. She's also the author of Beginning GIMP: From Novice to Professional.

Most Popular LinuxPlanet Stories