1

I have several lines of output, some lines contain information on jobs waiting example I want to select lines that have more than one occurrence of the pattern jobs waiting: 0

example:

abcdef rglk,jobs waiting: 2,blah,blah,jobs waiting:0,jobs running: 1,blah,blah
lbf(kjn fk)kkj,jobs waiting: 2,blah,blah,jobs running: 1,blah,blah
gdjhgvdjh,jobs waiting: 0,blah,blah,jobs running: 1,blah,blah,jobs waiting: 0
g gg,jobs waiting: 2,blah,jobs waiting: 0,jobs running: 1,blah,blah
kjn dikfc,jobs waiting: 0,blah,jobs waiting: 0,jobs running: 1,bl ah,blah
d1d,jobs waiting: 2,blah,blah,jobs running: 1,blah,blah
kjfdk nrf(lkj rgf),jobs waiting: 2,blah,blah,jobs waiting: 0,bl ah,blah

would work if the command only returns line 3 and line 5 I would also like to be able to select lines that are opposite to this Unfortunately I have no idea how to do this, with sed? awk? grep?

2 Answers 2

2

KISS grep approach:

grep 'jobs waiting: *0.*jobs waiting: *0' file

Invert by adding the -v command line switch.

Alternate with sed - attempt to replace the second instance, and print the line if it succeeds:

sed -n 's/jobs waiting: *0/&/2p' file

Inverse as

sed -n 's/jobs waiting: *0/&/2; t; p' file

Awk approach - use the return value of a gsub:

awk 'gsub(/jobs waiting: *0/,"&",$0) == 2' file

Invert as

awk 'gsub(/jobs waiting: *0/,"&",$0) != 2' file

(In all cases, *0 allows for zero or more space characters before the 0, consistent with your example.)

5
  • May I ask what is "KISS"?
    – Tim
    Commented Feb 16, 2019 at 1:26
  • @Tim KISS principle Commented Feb 16, 2019 at 1:28
  • Very nice! Sed using "grep-style" would be sed -n '/jobs waiting: *0.*jobs waiting: *0/p' file and sed -n '/jobs waiting: *0.*jobs waiting: *0/!p' file.
    – Freddy
    Commented Feb 16, 2019 at 1:38
  • Or grep -E '(jobs waiting: 0.*){2,}' file
    – Kusalananda
    Commented Feb 16, 2019 at 12:13
  • Thanks for the great answer! Cheers. (I think KISS stands for Keep IT Simple, Stupid. Commented Feb 17, 2019 at 23:36
0

You can use awk to get the desired lines as:

awk -F'jobs waiting: *0' 'NF > 2'

Where we split the records on the desired string, and should it contain at least 2 instances of it, the number of fields will be 3 or more.

HTH

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .