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.

2 Answers 2

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.

2
  • 1
    these second awk method worked flawlessly. Thank you!
    – pretz
    Commented Aug 3, 2020 at 14:39
  • 1
    Complementing Sundeep's answer. Here is another option: $ grep -B1 Minion ip.txt |grep -v Minion T5F6Z12: Commented Aug 4, 2020 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:

You must log in to answer this question.

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