Home > other >  How can I find a string that is separated into two lines in the file where I want to find it?
How can I find a string that is separated into two lines in the file where I want to find it?

Time:12-08

I need to look for a string in a text to know the line number in which it is located. My string is a single line that is divided into two lines in the file where I have to look for. Does anyone know how I can look for it? Thanks

My file.txt

Title number 1
Some random text

I need to find things like "number 1 Some random", "1 Some random"...

This is my code that only works if everything is in one line:

doc="file.txt"
text="number 1 Some random"
line=$(awk 'NR == awkvar='$text'' $doc)

Any suggestions? Thank you very much.

CodePudding user response:

$ cat tst.awk
BEGIN { OFS=": " }
NR>1 {
    cur = prev " " $0
    if ( index(cur,tgt) ) {
        print NR-1, cur
    }
}
{ prev = $0 }

$ awk -v tgt='number 1 Some random' -f tst.awk file
1: Title number 1 Some random text

If you ONLY want the line number printed then, of course, only do print NR-1.

CodePudding user response:

This might work for you (GNU sed & bash):

file="file.txt"
text="number 1 Some random"
line=$(($(sed -n 'N;/'${tgt// /\\s}'/!D;=;q' "$file")-1))

Build a regexp from text and use it in a sed script to report the line number of the match of the regexp.

N.B. If the match occurs within one line only the line number may be off by 1.

  • Related