How can I find a string in a file, then find the first instance of a line that contains 'srv' that precedes it.

I have been looking at Tac and sed, but have been unsuccessful at getting it to work right.

Output file to search looks like

srv-test-1 | SUCCESS | rc=0 >>
srv-test-2 | SUCCESS | rc=0 >>

The code prompts the user for the string they are looking for and stores it to a variable.

I am able to find the users request using

tac file | grep $requested

if the user requests b1, I would like it to return

b1 found on srv-test-2

and likewise if requesting a1 it would return

a1 found on srv-test-1
a1 found on srv-test-2
  • 1
    awk -v str=a1 '$0~str{print str" found on "srv}/^srv/{srv=$1}' file
    – mosvy
    Sep 9, 2019 at 18:51

3 Answers 3


If you're looking to do the search for multiple items, you could convert the whole file into a grep'able list of entries.

awk '/^srv/ { c = $1 ; next } { print $0 " found on " c }'

on the input file would give you

a1 found on srv-test-1
A3 found on srv-test-1
a1 found on srv-test-2
b1 found on srv-test-2
b2 found on srv-test-2
B3 found on srv-test-2
B4 found on srv-test-2

Then to search for a single item, you could filter the previous output

awk '/^srv/ { c = $1 ; next } { print $0 " found on " c }' | grep '^a1'

to give

a1 found on srv-test-1
a1 found on srv-test-2
$ requested='a1'; awk '$2=="|" { s=$1 }; $1==r { print r" found on "s }' r="$requested" file
a1 found on srv-test-1
a1 found on srv-test-2

The first part $2=="|" { s=$1 } assigns the content of the first field (srv-test-XX) to variable s if the second field is |.

The second part $1==r { print r" found on "s } compares the first field to variable r which holds the requested value. If it matches, we print the result.


You can do it using sed editor as shown:

str='a1';          #string to search
str_esc_lhs=$(printf '%s\n' "$str" | sed -e 's:[][\/.^$*]:\\&:g');# escaped var fit for use on the lhs 
S='[^[:blank:]]'; #regex for a nonwhitespace char

$ sed -e "
   s/\\(srv-$S*\\).*\\n\\(.*\\)/\\2 FOUND ON \\1/
" input_file.txt

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.