How to grep for a specific word and grab text
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.
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: