user1362373
user1362373

Reputation: 155

Extract numbers from strings

I have a file containing on each line a string of the form

string1.string2:\string3{string4}{number}

and what I want to extract is the number. I've searched and tried for a while to get this done using sed or bash, but failed. Any help would be much appreciated.

Edit 1: The strings may contains numbers.

Upvotes: 0

Views: 110

Answers (4)

chepner
chepner

Reputation: 532303

In bash:

sRE='[[:alnum:]]+'
nRE='[[:digit:]]+'
[[ $str =~ $sRE\.$sRE:\\$sRE\{$sRE\}\{($nRE)\} ]] && number=${BASH_REMATCH[1]}

You can drop the first part of the regular expression, if your text file is sufficiently uniform:

[[ $str =~ \\$sRE{$sRE}{($nRE)} ]] && number=${BASH_REMATCH[1]}

or even

[[ $str =~ {$sRE}{($nRE)} ]] && number=${BASH_REMATCH[1]}

Upvotes: 0

perreal
perreal

Reputation: 98118

Using sed:

sed 's/[^}]*}{\([0-9]*\)}/\1/' input_file 

Description:

[^}]*}      : match anything that is not } and the following }
{\([0-9]*\)}: capture the following digits within {...}
/\1/        : substitute all with the captured number

Upvotes: 2

Thor
Thor

Reputation: 47229

Use grep:

grep -o '\{[0-9]\+\}' | tr -d '[{}]'

Upvotes: 0

user647772
user647772

Reputation:

$ echo 'string1.string2:\string3{string4}{number}' |\
  cut -d'{' -f3 | cut -d'}' -f 1
number

Upvotes: 5

Related Questions