thetux4
thetux4

Reputation: 1633

Searching string in a file and outputting the line number

awk '$0 ~ str{print b}{b=$0}' str="findme" path_to_file

with this I can get the line before the found string's line.
How can I print its line number?

Upvotes: 2

Views: 14214

Answers (4)

William Pursell
William Pursell

Reputation: 212248

If I interpret the question correctly, and you simply want to print the line number of the line that precedes any line containing a given string, you can do:

$ awk '/findme/{print NR - 1}' /path/to/file

Upvotes: 3

Hai Vu
Hai Vu

Reputation: 40723

Here is a solution:

awk '$0 ~ str{print b;print}{b=$0}' str="findme" path_to_file

Or, if you don't mind a slightly different output, in which there are '--' separating groups of found lines:

grep -B1 findme path_to_file

In this case, you search for the string "findme" within the file 'path_to_file'. The -B1 flag says, "also prints 1 line before that."

Upvotes: 1

ninjalj
ninjalj

Reputation: 43688

Use NR to get the current line (record) number:

awk '$0 ~ str{print NR-1 FS b}{b=$0}' str="findme" path_to_file

Upvotes: 4

eyadof
eyadof

Reputation: 318

you can use echo $(awk '$0 ~ str{print b}{b=$0}' str="findme" path_to_file)

Upvotes: -1

Related Questions