【问题标题】:Search with grep only lines that start with #仅使用 grep 搜索以 # 开头的行
【发布时间】:2019-03-29 10:16:19
【问题描述】:

在我被踢之前,我想让你知道我检查了几个关于“grep”的文件,但我找不到我要找的东西,或者我的英语太有限,无法理解。

我有很多降价文档。每个文档都包含一个始终位于第 1 行的第一级标题 (#)。

我可以搜索 ^# 并且可以,但是我如何告诉 grep 在以 # 开头的行中查找某些单词?

我想要这个

grep 'some words' file.markdown

但还要指定该行以# 开头。

【问题讨论】:

    标签: regex unix terminal grep


    【解决方案1】:

    你可以使用

    grep '^# \([^ ].*\)\{0,1\}some words' file.markdown
    

    或者,使用 ERE 语法

    grep -E '^# ([^ ].*)?some words' file.markdown
    

    详情

    • ^ - 行首
    • # - 一个 # 字符
    • \([^ ].*\)\{0,1\} - 一个可选的模式序列(\(...\) 是 BRE 语法中的捕获组,在 ERE 中是 (...))(\{0,1\} 是一个间隔量词,它重复它修改 1 或 0 次的模式) :
      • [^ ] - 除空格外的任何字符
      • .* - 任何 0+ 个字符
    • some words - some words 文字。

    查看online grep demo

    s="# Get me some words here
    #some words here I don't want
    # some words here I need"
    grep '^# \([^ ].*\)\{0,1\}some words' <<< "$s"
    # => # Get me some words here
    #    # some words here I need
    

    【讨论】:

    • 非常感谢!这就是我一直在寻找的。点匹配任何字符,对吗?是否可以更具体地告诉 grep # 之后是一个空格
    • #\s.* 会这样做。
    • @ZoltanKing 当然,只需添加一个空格:grep '^# .*some words' file.markdown。或者,要匹配任何空格,grep '^#[[:space:]].*some words' file.markdown。除了[[:space:]],您还可以使用[[:blank:]](在这里,它们的行为相同)。
    • 谢谢!它可以工作,但是我只想匹配 # 之后的一个空格,而不是更多
    • @ZoltanKing 这不是问题,请参阅更新的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多