Nandu
Nandu

Reputation: 247

extract numbers or words before any special characters in unix shell scripting

I have some thing like this in a variable

10> 100 1000= 110

I would like to extract 10 and 1000 from this( 1st number before any special character given). The special characters mentioned here might change so this should work with any special characters like >,<,=.

Upvotes: 0

Views: 815

Answers (1)

anubhava
anubhava

Reputation: 786291

You can use gnu grep with -oP (PCRE) regex:

s='10> 100 1000=110'
grep -oP '[0-9]+(?=[<>=])' <<< "$s"

10
1000

RegEx Breakup:

  • [0-9]+: Match one or more digits
  • (?=[<>=]): Lookahead to assert there is a < or > or = characters ahead

Upvotes: 1

Related Questions