awk '$0 ~ str{print b}{b=$0}' str="findme" path_to_file
with th开发者_高级运维is I can get the line before the found string's line.
How can I print its line number?Use NR
to get the current line (record) number:
awk '$0 ~ str{print NR-1 FS b}{b=$0}' str="findme" path_to_file
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
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."
you can use echo $(awk '$0 ~ str{print b}{b=$0}' str="findme" path_to_file)
精彩评论