首页 > 解决方案 > grep 没有 macth 输出的字节点

问题描述

我正在使用一个grep

我只想输出偏移点。

但是现在我的命令被打印到offsetsmacthing-keywords上。

我的命令是

grep -Pbzo 'macthing-keywords' test.txt

输出是..

15 : macthing-keywords

我想要打印出 '15',代表偏移量(不是 macthing-keywords 被打印)

你能告诉我怎么做吗?

标签: unixgrep

解决方案


<space>:<space><anything that remains here>您可以使用sed类似的命令简单地删除任何内容,sed 's/ : .*//'或者您​​可以先删除所有:内容cut -d: -f1(如@bigdataolddriver建议的那样):

grep -Pbzo 'macthing-keywords' test.txt | sed 's/ : .*//'

或者

grep -Pbzo 'macthing-keywords' test.txt | cut -d: -f1

要输出到文件:

grep -Pbzo 'macthing-keywords' test.txt | sed 's/ : .*//' > outputfile.txt

如果每行有多个匹配项,则可能需要在运行之前将它们分开sedcut

xargs -0 | grep -Pbzo 'macthing-keywords' test.txt | \
  xargs -0 -n1 | cut -d: -f1 > outputfile.txt

或者,这似乎更安全,因为:...即使匹配包含换行符并且这些匹配延续也可能包含:在其中(但此解决方案需要sed支持\xXX符号),它也会删除:

xargs -0 | grep -Pbzo 'macthing-keywords' test.txt  | \
   sed 's/ *:[^\x00]*//g' | xargs -0 -n1 > outputfile.txt

xargs -0/对将xargs -0 -n1处理将 NUL 转换为换行符的匹配中断。


推荐阅读