【问题标题】:Limit grep to first match per line将 grep 限制为每行的第一个匹配项
【发布时间】:2020-03-03 14:12:12
【问题描述】:

我正在尝试查找在该行的第一个句点之前包含字母 a 的所有行。

这是一个示例文件:

test123a.hello
example.more-test-a.xyz
stacka.tester.this
nothing.nothing.nothing

在上面的例子中,我想grep这两行:

test123a.hello
stacka.tester.this

这是我尝试过的:

grep ".*a\." test.txt

这得到了我想要的 2 行,但它也得到了我不想要的这一行,因为 a 在第二个句号前面,而不是第一个句号:

example.more-test-a.xyz

如何将其限制为仅在第一个句点之前获取带有a 的行?

【问题讨论】:

    标签: regex linux shell command-line grep


    【解决方案1】:
    $ grep '^[^.]*a\.' test.txt
    test123a.hello
    stacka.tester.this
    
    • ^ 限制在行首匹配
    • [^.]* 匹配除. 字符以外的任何字符,零次或多次
    • a 字面匹配字符 a
    • \. 字面匹配字符 .


    这里也可以使用awk,更适合基于字段的处理

    $ # 'a' as last character for first field
    $ awk -F'.' '$1 ~ /a$/' test.txt
    test123a.hello
    stacka.tester.this
    
    $ # 'a' as last character for second field
    $ awk -F'.' '$2 ~ /a$/' test.txt
    example.more-test-a.xyz
    

    【讨论】:

    • awk中的相同正则表达式:awk '/^[^.]*a\./' file
    【解决方案2】:

    如果你觉得输出多,可以试试

    grep ".*a."测试.txt |少

    【讨论】:

    • 我不知道你在说什么,但我已经在使用相同的命令,你刚刚在它后面添加了| less,你并没有逃避这个时期......
    【解决方案3】:

    你可以试试[编辑]

    grep ".*a." test.txt | grep -v "\([^a]\.\)\{1,\}.*a."
    

    这将执行您的第一个 grep 并拒绝任何带有“a”的内容。前面有一个点。

    【讨论】:

    • 几乎可以做到,但它不会检测到这样的行:testa.helloa.example,因为第二个句点之前有一个a
    • 我编辑了答案,放置了一个条件,表示拒绝任何出现一个或多个点而没有成功的“a”。
    猜你喜欢
    • 2020-01-06
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多