Use grep to report back only line numbers
I have a file that possibly contains bad formatting (in this case, the occurrence of the pattern backslash
). I would like to use grep
to return only the line numbers where this occurs (as in, the match was here, go to line # x and fix it).
However, there doesn't seem to be a way to print the line number ( grep -n
) and not the match or line itself.
I can use another regex to extract the line numbers, but I want to make sure grep cannot do it by itself. grep -no
comes closest, I think, but still displays the match.
尝试这个:
grep -n "text to find" file.ext |cut -f1 -d:
If you're open to using AWK:
awk '/textstring/ {print FNR}' textfile
In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.
All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:
sed -n '/pattern/=' filename
链接地址: http://www.djcxy.com/p/19694.html
上一篇: 如何排除与grep或类似工具匹配的几行?
下一篇: 使用grep只回报行号