GREP to retrieve different lines

Quick to answer questions about finding your way around Linux Mint as a new user.
Forum rules
There are no such things as "stupid" questions. However if you think your question is a bit stupid, then this is the right place for you to post it. Stick to easy to-the-point questions that you feel people can answer fast. For long and complicated questions use the other forums in the support section.
Before you post read how to get help. Topics in this forum are automatically closed 6 months after creation.
Locked
knob
Level 3
Level 3
Posts: 100
Joined: Sat Nov 19, 2016 3:53 pm

GREP to retrieve different lines

Post by knob »

Good evening, could I retrieve both lines at the same time using grep (in one cmd line) ?
In other words, the first line (no matter the content) and all lines with THISLINE word.

for example :
Header line blabla....
line blabla.... blabla....
line THISLINE.... blabla....
line blabla.... blabla....
line blabla.... blabla....

the result :
Header line blabla....
line THISLINE.... blabla....
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
WharfRat

Re: GREP to retrieve different lines

Post by WharfRat »

You can use egrep 'Header|THISLINE' /file/to/search
knob
Level 3
Level 3
Posts: 100
Joined: Sat Nov 19, 2016 3:53 pm

Re: GREP to retrieve different lines

Post by knob »

thanks... anyway, how to pickup the first line instead of the word header ?
syg00

Re: GREP to retrieve different lines

Post by syg00 »

The grep manpage has a good write-up of elementary regex.
Some-how missed your followup q. That gets more difficult - I might move over to sed.
TI58C
Level 4
Level 4
Posts: 389
Joined: Tue Jul 18, 2017 5:57 am

Re: GREP to retrieve different lines

Post by TI58C »

Hi knob,

For problems like your 2nd question, I use awk. Try
awk '{if (NR==1 || $0 ~/THISLINE/){print}}'

In awk, every line is a record. What this awk statements do is: IF first record(=first line) OR(||) line($0) conforms to pattern (/THISLINE/) THEN print the line.

Patterns are regular expressions. They are invaluable when using grep / sed / tr / awk etc..

If you often have such problems, awk is very useful. To me it is like having a "mini-C" in bash/terminal.
And, unlike complicated sed expressions, You can actually read/understand them.

This is a good start with awk:
http://www.grymoire.com/Unix/Awk.html

And this for regexes:
http://www.grymoire.com/Unix/Regular.html

Kind regards,

Robert

btw:
WharfRat,
Believe egrep is old syntax, grep -E new/preferred?
Linux is like my late labrador lady-dog: loyal and loving if you treat her lady-like, disbehaving princess if you don't.
Locked

Return to “Beginner Questions”