Strip leading and numbers from a string.

Hello I have two vars loaded with
$VAR1="ISOMETHING103"
$VAR2="COTHERTHING04"

I need to:
1) Strip the first char. Could be sed 's/^.//'
2) The number has it's rules. If it has "hundreds", it needs to be striped.
If it is just two digits it shouldn't.
So, for VAR1 output should be "SOMETHING03".
And for VAR2 output should be "OTHERTHING04".
My main issue here is how can I strip the "hundreds"?
Input would be all caps always.

Thanks in advance,
Sebastian

PS you have posted 12 post here, you should now that you need to use Code Tags

1)

echo ${VAR1:1}
SOMETHING103

Here's one way using awk:

nawk '{x=length($0); if (substr($0,x-2,1) ~ "[0-9]") {print substr($0,2,x-4) substr($0,x-1,2) } else {print substr($0,2,x-1)} }' filename
SOMETHING03
OTHERTHING04

other awk

echo ${VAR1:1} | awk '{l=length($0);m=match($0,/[0-9]/)} {if (l-m==2) {print substr($0, 1,m-1)substr($0, m+1,2)} else {print}}'
1 Like
echo "ISOMETHING103" | awk ' {
        match ($0, /^[A-Z]*/)
        printf substr($0, RSTART + 1, RLENGTH - 1)
        match ($0, /[0-9]*$/)
        print (RLENGTH >= 3 ? substr($0, RSTART + 1) : substr($0, RSTART))
} '
1 Like

If you're using a 1993 or later version of the Korn shell:

#!/bin/ksh
VAR1="ISOMETHING103"
VAR2="COTHERTHING04"
printf "Initial VAR1=\"%s\", VAR2=\"%s\"\n" "$VAR1" "$VAR2"
VAR1=${VAR1/?/}
VAR2=${VAR2/?/}
VAR1=${VAR1/%[0-9]([0-9][0-9])/\1}
VAR2=${VAR2/%[0-9]([0-9][0-9])/\1}
printf "  Final VAR1=\"%s\", VAR2=\"%s\"\n" "$VAR1" "$VAR2"

will yield:

Initial VAR1="ISOMETHING103", VAR2="COTHERTHING04"
  Final VAR1="SOMETHING03", VAR2="OTHERTHING04"

If you're using a recent bash:

#!/bin/bash
VAR1="ISOMETHING103"
VAR2="COTHERTHING04"
printf "Initial VAR1=\"%s\", VAR2=\"%s\"\n" "$VAR1" "$VAR2"
VAR1=${VAR1/?/}
VAR2=${VAR2/?/}
VAR1=${VAR1/%[0-9][0-9][0-9]/${VAR1:$((${#VAR1} - 2))}}
VAR2=${VAR2/%[0-9][0-9][0-9]/${VAR2:$((${#VAR2} - 2))}}
printf "  Final VAR1=\"%s\", VAR2=\"%s\"\n" "$VAR1" "$VAR2"

produces the same output.
Both of these suggestions use parameter expansions that are extensions that are allowed, but not specified, by the standards.

1 Like
$ echo $VAR1 | sed 's/.//;s/[0-9]\([0-9]\{2\}\)$/\1/'
SOMETHING03
$ echo $VAR2 | sed 's/.//;s/[0-9]\([0-9]\{2\}\)$/\1/'
OTHERTHING04
1 Like

Thanks, will use them from now on :slight_smile:

---------- Post updated at 01:34 PM ---------- Previous update was at 01:26 PM ----------

I am amazed! Thanks a lot for your quick answers.
It looks to me that the awk solution is the more "portable" option, and since this needs to be used in many flavors of Linux/Unix, y expect to work ok.
I will report back
Very very very thank you to all of you.
Sebastian