1

Hello I have a fairly simple question I want to search for only the last '1+1' before the = sign from this statement

1+1+1+1+1+1=6

I have tried the grep statement

`grep '.+' 'text.txt'`

it returns

1+1+1+1+1+

as it highlights all of the + symbols. I believe I need to create a min range such as: grep '.+{4,}' 'text.txt' This does not work, can anyone explain why? A solution with explanation would be appreciated.

Thanks

1
  • Doesn't grep return the whole line when it finds the string? Commented Nov 20, 2014 at 21:07

2 Answers 2

1

To get the last +-expression you could use grep -o and pipe that into tail -1:

grep -o '[0-9]+[0-9]' <<< '1+1+1+1+2+1=6' | tail -1

This regex matches a number (between 0 and 9) [0-9], followed by a literal + sign, followed by a number again. That will match more than one part of your expression string. The -o option prints each match on a separate line, and the tail selects the last one of these lines.

If you have the expression in a file text.txt, just use:

grep -o '[0-9]+[0-9]' text.txt | tail -1
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works but i really dont understand how it does it. Why 0-9 + 0-9? Edit- I see you edited your comment to explain it. Cheers!
@user3423572 I'll add an explanation.
1

+ is a metacharacter that means "1 or more of the previous match". When you say .+ you're saying "any character, and then 1 or more of any character."

If you want to search for a literal metacharacter, you must escape it with a backslash.

grep '.\+' text.txt

1 Comment

This may vary by system and grep-family you're using - + is a normal character for basic regular expressions, unless it is escaped to become a metacharacter = grep == grep -G 'a+' finds literal a+ but grep 'a\+' finds one or more a in a sequence; while it's opposite for egrep == grep -E 'a+' the + is already a metacharacter, so grep -E 'a+' finds one or more a but grep -E 'a\+' escapes the meta + and matches literal a+ — based on man 1 grep for "BSD General Commands" on OS X. An online page for man 1 grep on Linux tells me it's the same, but I haven't tested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.