Reputation: 21029
Given the string in some file:
hel string1
hell string2
hello string3
I'd like to capture just hel
using cat file | grep 'regexp here'
I tried doing a bunch of regexp but none seem to work. What makes the most sense is: grep -E '\Ahel'
but that doesn't seem to work. It works on http://rubular.com/
however. Any ideas why that isn't working with grep
?
Also, when pasting the above string with a tab space before each line, the \A
does not seem to work on rubular
. I thought \A
matches beginning of string, and that doesn't matter whatever characters was before that. Why did \A
stop matching when there was a space before the string?
Upvotes: 3
Views: 395
Reputation: 41450
Using awk
awk '$1=="hel"' file
PS you do not need to cat file to grep, use grep 'regexp here' file
Upvotes: 0
Reputation: 10136
ERE (-E
) does not support \A
for indicating start of match. Try ^
instead.
Use -m 1
to stop grepping after the first match in each file.
If you want grep to print only the matched string (not the entire line), use -o
.
Use -h
if you want to suppress the printing of filenames in the grep output.
Example:
grep -Eohm 1 "^hel" *.log
If you need to enforce only outputting if the search string is on the first line of the file, you could use head
:
head -qn 1 *.log | grep -Eoh "^hel"
Upvotes: 3
Reputation: 19423
I thought \A matches beginning of string, and that doesn't matter whatever characters was before that. Why did \A stop matching when there was a space before the string?
\A
matches the very beginning of the text, it doesn't match the start-of-line when you have one or more lines in your text.
Anyway, grep doesn't support \A
so you need to use ^
which by the way matches the start of each line in multi-line mode contrary to \A
.
Upvotes: 1
Reputation: 785316
ERE doesn't support \A
but PCRE does hence grep -P
can be used with same regex (if available):
grep -P '\Ahel\b' file
hel string1
Also important is to use word boundary \b
to restrict matching hello
Alternatively in ERE you can use:
egrep '^hel\b'
hel string1
Upvotes: 2