Thursday, February 17, 2022

[SOLVED] Search with grep only lines that start with #

Issue

before i get my ass kicked, I want you to know that I checked several documents on "grep" and I couldn't find what I'm looking for or maybe my English is too limited to get the idea.

I have a lot of markdown documents. Each document contain a first level heading (#) which is always on line 1.

I can search for ^# and that works, but how can I tell grep to look for certain words on the line that starts with #?

I want this this

grep 'some words' file.markdown

But also specify that the line starts with a #.


Solution

You may use

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

Or, using ERE syntax

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

Details

  • ^ - start of a line
  • # - a # char
  • \([^ ].*\)\{0,1\} - an optional sequence of patterns (a \(...\) is a capturing group in BRE syntax, in ERE, it is (...)) (\{0,1\} is an interval quantifier that repeats the pattern it modifies 1 or 0 times):
    • [^ ] - any char but a space
    • .* - any 0+ chars
  • some words - some words text.

See an 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


Answered By - Wiktor Stribiżew
Answer Checked By - Timothy Miller (WPSolving Admin)