【问题标题】:GREP: is there a way to use grep inserting a text between filename and the pattern?GREP:有没有办法使用 grep 在文件名和模式之间插入文本?
【发布时间】:2019-01-09 15:58:01
【问题描述】:

我有grep --color -EH "^([^,]*\,){3}5" try.csv

它的输出是这样的:

try.csv:410,30151010,K,5001,,,,,,,,,,,,,,,,,,,,,,,,,,,,,512
try.csv:652,20151010,K,5001,,,,,,,,,,,,,,,,,,,,,,,,,,,,,41
try.csv:109,30151010,R,5005,,,,,,,,,,,,,,,,,,,,,,,,,,,,,455

我试过grep --color -EH "^([^,]*,){3}5" try.csv | perl -ne 'print ",$_"'

但输出看起来像这样:

,try.csv:410,30151010,K,5001,,,,,,,,,,,,,,,,,,,,,,,,,,,,,512
,try.csv:652,20151010,K,5001,,,,,,,,,,,,,,,,,,,,,,,,,,,,,41
,try.csv:109,30151010,R,5005,,,,,,,,,,,,,,,,,,,,,,,,,,,,,455

预期输出:

try.csv:,410,30151010,K,5001,,,,,,,,,,,,,,,,,,,,,,,,,,,,,512
try.csv:,652,20151010,K,5001,,,,,,,,,,,,,,,,,,,,,,,,,,,,,41
try.csv:,109,30151010,R,5005,,,,,,,,,,,,,,,,,,,,,,,,,,,,,455

我对 Perl 和 shell 很陌生。我正在 CSV 文件中搜索。

【问题讨论】:

  • perl -pe's/^try.csv:\K/,/'
  • sed 's/^[^:]*:/&,/'
  • sed 工作得非常好。谢谢。 CWLiu 你能向我解释一下这是如何工作的吗?
  • @CWLiu: sed 's/^[^:]*:/&,/'sed 's/:/&,/' 相同

标签: shell perl unix grep


【解决方案1】:

您可以使用sed插入逗号,

$ grep --color -EH "^([^,]*\,){3}5" try.csv | sed 's/:/&,/'

s/:/&,/:替换中的特殊字符 & 指的是匹配的字符串部分。您可以在& 后面添加一个逗号以满足您的要求。

【讨论】:

  • 无需锚定正则表达式并将所有内容匹配到第一个冒号。 /:/ 自己会匹配第一个冒号,sed 's/:/&,/' 就足够了。
猜你喜欢
  • 1970-01-01
  • 2017-06-26
  • 2014-09-10
  • 1970-01-01
  • 2015-02-13
  • 2017-11-01
  • 2012-07-24
  • 2015-09-09
  • 1970-01-01
相关资源
最近更新 更多