4

I have a text file which lists a hostname and in the line directly under states the results of a ping of a salt minion. Here is an example output:

T5F6Z12:
   Minion did not return. [Not connected]

I need to be able to first identify is the text (Minion did not return) exists and if so grab the hostname associated with the error so I can run other commands against that server.

I have started with this:

if grep -q "Minion" /srv/salt/test/ping_results
then
    

So I'm pretty sure I need to grep for the word "Minion" because it will only show up for servers that failed the test. But once I've identified it exists, I'm not sure how to grab the associated hostname above it in the text file.

8

You could use -B1 to print previous line as well and then grab only the first line:

$ grep -B1 'Minion' ip.txt
T5F6Z12:
   Minion did not return. [Not connected]
$ grep -B1 'Minion' ip.txt | head -n1
T5F6Z12:

Or, do it with awk:

$ awk '/Minion/{print p} {p=$0}' ip.txt
T5F6Z12:
$ awk '/Minion/{sub(/:$/, "", p); print p} {p=$0}' ip.txt
T5F6Z12

Here p keeps saving the last line. When input line contains Minion, then it gets printed. Note that this will work for multiple matches unlike the grep solution above which gives only the first match.

| improve this answer | |
  • 1
    these second awk method worked flawlessly. Thank you! – Sean Patterson Aug 3 at 14:39
  • 1
    Complementing Sundeep's answer. Here is another option: $ grep -B1 Minion ip.txt |grep -v Minion T5F6Z12: – Hopping Bunny Aug 4 at 17:29
2

If you are tied to grep then you could maintain multi-line matches ...

file:

T5F6Z12:
   Minion did not return. [Not connected]
T5F6Z11:
   Pinion did return. [connected]
T5F6Z10:
   Minion did not return. [Not connected]

Using

grep -B 1 "Minion" file | grep ":$"
T5F6Z12:
T5F6Z10:

If you can use sed then there is an answer over here in U&L which I have plagiarised below

sed -n '/Minion/{x;p;d;}; x' file
T5F6Z12:
T5F6Z10:
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.