Match pattern and get lines numbers in a vector

Hi everyone,
I am new to shell scripting, and would appreciate your help on following problem.

I need to search a file for a pattern, then get the number of each line that matches the given pattern.
Then I need to search those specific line numbers from the first file in a second file and print the entire lines.

I tried with grep -n 'pattern' from the first file, which gives me:

21: pattern
37: pattern
58: pattern
...

now I need to get 21,37,58... in a vector or something, and display these lines from the second file.

I hope I made myself clear.

thanks in advance

Post samples of the input files and the desired output.

file1:

ldap_bind_s
ldap_bind_s
ldap_bind_s
ldap_bind_proxy
ldap_bind_s
ldap_bind_s
... etc

file2:

John Smith
Martin King
Octavius Papadocoluos
Helen Mayweather
Johnatan Stick
...etc

I need to search in file1 for pattern=ldap_bind_proxy, and display the name of the person at the same line number from file2
e.g. in above example, it would be Helen Mayweather, located at line number 4

Thank you

---------- Post updated at 01:22 PM ---------- Previous update was at 01:20 PM ----------

I tried:

cat file1.txt | grep -n 'ldap_bind_proxy' | var=`cut -d ':' -f1` | sed -n '"$var"p' file2.txt

but something isn't going well

This will give you both the pattern and the record from the second file:

% paste file1 file2 | grep -F 'ldap_bind_proxy'
ldap_bind_proxy Helen Mayweather

With awk

awk 'NR == FNR {
  $0 ~ p && nr = NR 
  next
  }
FNR == nr
  ' p='ldap_bind_proxy' file1 file2
1 Like

Thank you radoulov. for your reply.
Can you please explain a bit, the code meaning, because it only displays only the last match and not all of them, so I can modify it accordingly.

thanks

This should work:

awk 'NR == FNR {
  $0 ~ p && nr[NR] 
  next
  }
FNR in nr
  ' p='ldap_bind_proxy' file1 file2

While reading the first input file ( NR ==FNR ), build an array named nr containing the record numbers of the matching records.
While reading the second input file, print the records whose record numbers match the keys of the array nr.

it worked perfectly!
thanks a lot!