How would you perform a grep for text that appears on two lines?
For example:
pbsnodes
is a command I use that returns the utilization of a linux cluster
root$ pbsnodes
node1
state = free
procs = 2
bar = foobar
node2
state = free
procs = 4
bar = foobar
node3
state = busy
procs = 8
bar = foobar
I want to determine the number of procs that match nodes that are in state 'free'. So far I have been able to determine the "number of procs" and "the nodes in free state", but I want to combine them into one command that shows all free procs.
In the above example, the correct answer would be 6 (2+4).
What I have
root$ NUMBEROFNODES=`pbsnodes|grep 'state = free'|wc -l`
root$ echo $NUMBEROFNODES
2
root$ NUMBEROFPROCS=`pbsnodes |grep "procs = "|awk '{ print $3 }' | awk '{ sum+=$1 } END { print sum }'`
root$ echo $NUMBEROFPROCS
14
How can I search for every line that reads 'procs = x', but only if the line above it reads 'state = free?
awk
does pattern matching; you don't needgrep
: see Stephane's answer – jasonwryan Sep 30 '13 at 22:01sed
does pattern matching as well. You could also useperl
, orphp
, or what ever language you prefer. But at least the headline of the question asked for multi line grep... ;-) – binfalse Sep 30 '13 at 22:18awk
anyways... :) – jasonwryan Sep 30 '13 at 23:48