1

I have a text file that looks like this:

landlord: John Smith
  has:
    house: 0
    flat: 5
  available: 1
  cheap: 0
  quality: 1
landlord: Will Hall
  has:
    house: 3
    flat: 4
  available: 1
  cheap: 1
  quality: 0
landlord: Marry Moe
  has:
    house: 0
    flat: 2
  available: 1
  cheap: 1
  quality: 0

All I am interested in is landlord and available lines. How to grep the available: 1 line by landlord ? I mean cat filename | grep -i 'landlord: John Smith' and then check if available is 1 or 0 ?

John Smith
  • 11
  • 2
  • `grep -i 'landloard: John Smith'` - you meant `landlord`? – Arkadiusz Drabczyk Jan 17 '21 at 20:53
  • 3
    If you have any influence over the format here, I think it might be worth changing it from what seems to be "almost yaml" to actually being proper yaml, in which case you would have proper tooling readily available. Pretending that this is plain text may work to some extent, but it seems like the robust solution would be to actually treat it as the structured data that it is. – Håkan Lindqvist Jan 17 '21 at 20:56

2 Answers2

3

Here is one way to do it:

egrep "(landlord|available)" filename | grep -A1 "John Smith"

UPD to check availability:

egrep "(landlord|available)" filename | grep -A1 "John Smith" | grep -c "available: 1"
jabbson
  • 720
  • 2
  • 9
  • Nice one, but grep will exit with 0 status (success) as it is searching for `John Smith` and not the `available: 1`. It should check if `John Smith` is `available: 1` if no - exit with status 1. – John Smith Jan 17 '21 at 21:04
  • throw another grep at it and see if available: 1 is in there, updated the answer – jabbson Jan 17 '21 at 21:19
1

You can use this command for the same:

grep -A 4 -i 'John Smith' test.txt | grep -i available

asmath
  • 319
  • 1
  • 6