在python的regex (re)库中,我可以执行re.search("<pattern>", string).start()
以获得模式的开始(如果模式存在)。
如何在unix命令行工具grep
中执行相同操作?
。如果=";th.n"字符串"somethingwrong">,我希望看到数字5(考虑到以1为基础,但以0为基础的4也可以)
谢谢!
例如:
echo "abcdefghij" | grep -aob "e"
输出:
4:e
:
-b获取字节偏移
-a告诉grep使用输入作为文本
-o输出结果
用你的例子:
echo ""somethingwrong"" | grep -aob "th.n"
4:thin
这适用于多个匹配:
echo "abcdefghiqsdqdqdfjjklqsdljkhqsdlf" | grep -aob "f"
5:f
16:f
32:f
也许Perl一行程序是必须编写Python程序和标准Unix工具的简单性之间的一个令人满意的折衷。
给定这个文件:
$ cat foo.txt
This thing
that thing
Not here
another thing way over here that has another thing and a third thing
thank you.
可以运行以下Perl一行代码:
$ perl -lne'while(/th.n/g){print $.," ",$-[0]," ",$_;}' foo.txt
1 5 This thing
2 5 that thing
4 8 another thing way over here that has another thing and a third thing
4 45 another thing way over here that has another thing and a third thing
4 63 another thing way over here that has another thing and a third thing
5 0 thank you.
另外,grepllike搜索工具ack(我编写的)有一个--column
选项来显示列:
$ ack th.n --column foo.txt /dev/null
foo.txt
1:6:This thing
2:6:that thing
4:9:another thing way over here that has another thing and a third thing
5:1:thank you.
或者使用--nogroup
选项,以便文件名出现在每行。
$ ack th.n --column --nogroup foo.txt /dev/null
foo.txt:1:6:This thing
foo.txt:2:6:that thing
foo.txt:4:9:another thing way over here that has another thing and a third thing
foo.txt:5:1:thank you.
我必须添加对/dev/null的搜索,因为如果只搜索一个文件,ack的输出将会不同。
ripgrep也有一个--column
选项。
$ rg --column --line-number th.n foo.txt
1:6:This thing
2:6:that thing
4:9:another thing way over here that has another thing and a third thing
5:1:thank you.