MOHAMED
MOHAMED

Reputation: 43558

How to extract a part of string?

I have string contains a path

string="toto.titi.1.tata.2.abc.def"

I want to extract the substring which is situated after toto.titi.1.tata.2.. but 1 and 2 here are examples and could be other numbers.

In general: I want to extract the substring which situated after toto.titi.[i].tata.[j]..

[i] and [j] are a numbers

How to do it?

Upvotes: 0

Views: 200

Answers (7)

chepner
chepner

Reputation: 532013

An alternate bash solution that uses parameter expansion instead of a regular expression:

echo "${string#toto.titi.[0-9].tata.[0-9].}"

If the numbers can be multi-digit values (i.e., greater than 9), you would need to use an extended pattern:

shopt -s extglob
echo "${string#toto.titi.+([0-9]).tata.+([0-9]).}"

Upvotes: 5

Kent
Kent

Reputation: 195209

try this awk line:

awk -F'toto\\.titi\\.[0-9]+\\.tata\\.[0-9]+\\.' '{print $2}' file

with your example:

kent$  echo "toto.titi.1.tata.2.abc.def"|awk -F'toto\\.titi\\.[0-9]+\\.tata\\.[0-9]+\\.' '{print $2}'
abc.def

Upvotes: 0

dogbane
dogbane

Reputation: 274778

Pure bash solution:

[[ $string =~ toto\.titi\.[0-9]+\.tata\.[0-9]+\.(.*$) ]] && result="${BASH_REMATCH[1]}"
echo "$result"

Upvotes: 6

hek2mgl
hek2mgl

Reputation: 158140

You can use sed. Like this:

string="toto.titi.1.tata.2.abc.def"
string=$(sed 's/toto\.titi\.[0-9]\.tata\.[0-9]\.//' <<< "$string")
echo "$string"

Output:

abc.def

Upvotes: 0

phoxis
phoxis

Reputation: 61950

May be like this:

echo "$string" | cut -d '.' -f 6-

Upvotes: 0

thb
thb

Reputation: 14464

This does it:

echo ${string} | sed -re 's/^toto\.titi\.[[:digit:]]+\.tata\.[[:digit:]]+\.//'

Upvotes: 0

jh314
jh314

Reputation: 27812

You can use cut

 echo $string | cut -f6- -d'.'

Upvotes: 1

Related Questions