Search word in a line and print earlier pattern match

Hi All,
I have almost 1000+ files and I want to search specific pattern. Looking forwarded your input.

Search for: word1.word2 (Which procedure contain this word, I need procedure name in output.

Expected output:
procedure test1
procedure test2
procedure test3
procedure test4

File Contain:
procedure test1
a:=word1.word2;
end;

procedure

test2
a:= word1.word2;
end;

procedure test3
a := word1.word2;
end;

procedure test4
a :=word1.word2;
end;

procedure test5
a :=word1.word3;
end;

procedure test6
a :=word1.word3;
end;

To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags

```text
 and 
```

by hand.)

Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums

---------- Post updated at 19:37 ---------- Previous update was at 19:28 ----------

Try something like this:

 awk '/procedure/{s=$0;f=1}/word1\.word2/ && f{print s;f=0}' file
grep -B1 "word1\.word2" input_file

Hi Franklin, thanks for reply, however this is not working for procedure test2. test2 is missing, the only issue because test2 available in new line. Can you pls reframe this as I am not that good in unix. Appreciate your quick response.

---------- Post updated at 12:46 PM ---------- Previous update was at 12:45 PM ----------

Hi Franklin, thanks for reply, however this is not working for procedure test2. test2 is missing, the only issue because test2 available in new line. Can you pls reframe this as I am not that good in unix. Appreciate your quick response.

Try this one:

awk '
/procedure/{s=$0;f=1}
/^test[0-9]/{s=s FS $0}
/word1\.word2/ && f{print s;f=0}
' file

Regards

Hi Franlin, Thanks again for response, however looks like you have placed hardcoded test, this name is not fixed. I can be anything, so I am looking for any word which is coming right after keyword procedure, that needs to be printed.

Something like this?

awk '/procedure/{
  s=$0; f=1
  if(length < 10){
    line=""
    while(!line){getline line}
    s=s FS line
  }
}
/word1\.word2/ && f{print s;f=0}
' file

Here comes the longest SED I ever wrote:

sed -e '{/^$/d;/^end\;$/d;}' yy.txt | \
sed -e '/^procedure$/{N;s/\n/ /;}' -e '{N;s/\n/ /;}' \
-e '/word1.word2/!d; s/^\([[:alnum:]]* [[:alnum:]]*\) \(.*\)/\1/'

Dont know what is you version of SED.
Check if [[:alnum:]] is available.