0

This code is for check if a character is a integer or not (i think). I'm trying to understand what this means, I mean... each part of that line, checking the GREP man pages, but it's really difficult for me. I found it on the internet. If anyone could explain me the part of the grep... what means each thing put there:

echo $character | grep -Eq '^(\+|-)?[0-9]+$'

Thanks people!!!

2 Answers 2

4

Analyse this regex:

'^(\+|-)?[0-9]+$'

^ - Line Start
(\+|-)? - Optional + or - sign at start
[0-9]+ - One or more digits
$ - Line End

Overall it matches strings like +123 or -98765 or just 9

Here -E is for extended regex support and -q is for quiet in grep command.

PS: btw you don't need grep for this check and can do this directly in pure bash:

re='^(\+|-)?[0-9]+$'
[[ "$character" =~ $re ]] && echo "its an integer"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man... im trying to understand all this stuff in linux, i'm very new in this.. i'll keep on trying
Here i found this, for anyone who need it: tldp.org/LDP/abs/html/x17046.html
1

I like this cheat sheet for regex:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

It is very useful, you could easily analyze the

'^(+|-)?[0-9]+$'

as

  • ^: Line must begin with...
  • (): grouping
  • \: ESC character (because + means something ... see below)
  • +|-: plus OR minus signs
  • ?: 0 or 1 repetation
  • [0-9]: range of numbers from 0-9
  • +: one or more repetation
  • $: end of line (no more characters allowed)

so it accepts like: -312353243 or +1243 or 5678
but do not accept: 3 456 or 6.789 or 56$ (as dollar sign).

Comments

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.