Comsciers
Comsciers

Reputation: 154

Regular Expression to match exactly the digits after the first dot in a string

I have a two string like the example below,

string_1 = XXXXXXX.98.X131.X001
string_2 = XXXXXXX.X131.X001

I want to split the string_1 on the 2nd dot as the 1st dot is followed by a digit and I want to split the string_2 on the 1st dot as the 1st dot is not followed by a digit

Code is as below for

For String_1 as the input:

#!/bin/bash
name='XXXXXXX.98.X131.X001'
if [[ $name =~ [/\.\d\.] ]]; then
    name=$(echo $name | cut -d'.' -f -2) 
    echo $name
else
    name=$(echo $name | cut -d'.' -f1)
    echo $name
fi

Below is the output

XXXXXXX.98

For String_2 as the input:

#!/bin/bash
name='XXXXXXX.X131.X001'
if [[ $name =~ [/\.\d\.] ]]; then
    name=$(echo $name | cut -d'.' -f -2) 
    echo $name
else
    name=$(echo $name | cut -d'.' -f1)
    echo $name
fi

Below is the output

XXXXXXX.X131

instead of

XXXXXXX

what is the best way to check if dot is followed digit or a character

Upvotes: 1

Views: 166

Answers (1)

oguz ismail
oguz ismail

Reputation: 50775

Use a parameter expansion instead.

$ name=XXXXXXX.98.X131.X001
$ echo "${name%%.[![:digit:]]*}"
XXXXXXX.98
$ name=XXXXXXX.X131.X001
$ echo "${name%%.[![:digit:]]*}"
XXXXXXX

The %%.[![:digit:]]* part removes the longest trailing substring that starts with a dot and a non-digit character from name.

Upvotes: 3

Related Questions