Easy(?) problem for shell script writers

Lee Woodbury leland at cs.columbia.edu
Tue May 14 07:24:42 AEST 1991


In article <1991May9.151138.21246 at uvm.edu> moore at emily.uvm.edu (Bryan Moore) writes:
>I am trying to write a shell script (AIX 3.1 ksh) that does the following,
>takes the output from an (awk) command, say
>
>STRING1
>STRING2
>STRING3
>
>and use each of those strings as a parameter to the fgrep of
>a system call. 
>
>I want to do a 'ps | fgrep $1' where $1 is each of the above
>strings, but obviously the above is incorrect. 
>
>There must be an easy way to do this. I hope my explanation
>is understandable.

If you mean that the STRINGs are patterns for which you're searching
the ps output (as opposed to fgrep command-line options you're
assembling), then the following may be helpful.

Unless you have some (hidden) reason to use fgrep, you can get a fast
and elegant solution using the more powerful egrep, without resorting
to temporary files or multiple calls to ps (as suggested by some other
responses to your query), as follows:

	ps | egrep "$(your_awk_script)"

This presumes that your_awk_script outputs newline-separated patterns
(as you show in your example), which will thus adhere to the syntax of
egrep's alternation (OR) pattern.

If your_awk_script outputs space-separated patterns, then you'll have
to filter the output through sed, like so:

	ps | egrep "$(your_awk_script | sed 's/ /|/g')"

In this case, the sed script replaces the spaces between
your_awk_script's output patterns with vertical bars, which are the
same as newlines as far as egrep is concerned.

[ Note: The query specified (AIX 3.1) ksh.  Bourne shell users should
replace the $(command substitution) syntax shown in these examples with
the more familiar `backquoting` mechanism used in both sh and ksh. ]

Note that egrep is generally faster than fgrep anyway, and obviously
so if you have to run it multiple times on the output of ps to get
what you want.

If you must use fgrep (for reasons you haven't given), then you'll have
to save the output of ps to a temporary file and, in a loop bounded by
the number of search patterns output by your_awk_script, fgrep the ps
output once for each of those patterns, as shown in at least one
earlier response.

Hope this helps.

Leland Woodbury
-- 
INTERNET: leland at cs.columbia.edu
  USENET: ...!columbia!cs.columbia.edu!leland
  BITNET: leland%cs.columbia.edu at cuvmb
  USMAIL: Columbia Univ., 457 CS, 500 W. 120 St., NYC 10027-6699



More information about the Comp.unix.aix mailing list