SOLVED: Using grep to display from the start of match

dude

New Member
Joined
Nov 9, 2020
Messages
3
Reaction score
1
Credits
24
Can grep be used only show results from the start of match? Example, there is a text file with...

iliketurtles
iliketurtles
[TAB]iliketurtles
asgfhasfgshailiketurtles
^%&%&%*&iliketurtles

The results I want to return would look like...

iliketurtles
iliketurtles
iliketurtles
iliketurtles
iliketurtles

I know that '^iliketurtles*. will return the results if the line starts with it, this is not what I need. I need from the start of the match.
 


delete
 
Last edited:
The results I want to return would look like...

iliketurtles
iliketurtles
iliketurtles
iliketurtles
iliketurtles
Assuming your text file is named turtles.txt -- try this:
Code:
grep -o "iliketurtles" turtles.txt

To be clear, it is not grepping everything from the start of the match. It is only grepping the match inside the quotes. Anything following the match would also be removed.
 
Last edited:
And if you had something like:
blahblahblahiliketurtlesblahblahblah
And you want to see “iliketurtlesblahblahblah”
Off the top of my head - you could do something like this:
Bash:
grep -Poz 'iliketurtles(.*\n)'
Above, -P uses Perl style regular expressions, -o will only match things that exactly match the regex and -z allows us to match new lines with \n.
The regex matches anything in a line which contains iliketurtles followed by zero or more of any characters until the end of the line.
 
Last edited:
I get...

bash: syntax error near unexpected token `('
 
I get...

bash: syntax error near unexpected token `('

Ah! Sorry - I wrote the reply on my so called smartphone earlier - It was using the wrong single quote characters. That was what caused the bash error.
Also, I noticed my phone had inserted an extra asterisk near the end of the line, before the closing single quote too - which would have yielded a wrong result too!

I've edited my previous post to fix the single quotes and remove the unneeded asterisk. That should work now.
Sorry again about that!
 
In fact - I don't know why I went with the Perl regex option at all.....
This would do the trick and be even simpler:
Bash:
egrep -o "iliketurtles.*"

Mind you, I did post it this morning. I've been off caffeine for a while now, so it takes a while for my brain to fully boot and get up to speed nowadays!
Damn my morning brain! Ha ha!
 

Members online


Top