5.2. The grep command

grep is used to search a certain pattern in a file. The syntax of the command is

grep options pattern file ...

This searches in all files given for lines where the pattern matches. For pattern we use a regular expression. If we want to use extended regular expressions we can use the option -E or use the egrep-command. grep can also read from standard input. So it is possible to send the output of a command to grep using a pipe. For example, searching all three letter commands in /usr/bin can be done as

% ls /usr/bin | grep ^...$

There are also other possibilities for this.

For options for grep, you can consult the man-page. There are options to display only the number of matches, only the filenames wherein the pattern matches, show everything that doesn’t match, show 2 lines before and 2 lines after every matching line …




Exercises


  1. In a gaussian optimization, you can check if the geometry is converged by searching for the following pattern:

    Maximum Force            0.291717     0.000450     NO
    RMS     Force            0.044663     0.000300     NO
    Maximum Displacement     0.595019     0.001800     NO
    RMS     Displacement     0.203024     0.001200     NO
    

    Find a grep pattern that displays these lines from a gaussian outputfile. An example file is /data/tccm/linux_bash/5/fenol.log

  2. On dirac, we have a command qtot which shows the state of the queueing system. You can simulate this command by cat /data/tccm/linux_bash/5/qtot. Use grep and pipes for the following:

    • show the list of running jobs, of queued jobs

    • show the list of jobs beloning to some user (of your choice)

    • show the list of running jobs of some user

    • show the number of running jobs of some user

    • show all jobs running or queued in a “g-queue”. The queue name is the third column in the output.