Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the 2nd and 4th character from a string

I have a script that emails database information for a website to me. However I need to grab the 2nd and 4th character of the domain name as two variables in my bash script.

Currently I have the following for getting the second level domain name.

DOMAINNAME=`echo ${NEW_DOMAIN_NAME} | grep -oE '/[^/]+' | cut -c6- | rev | cut -c4- | rev`

But now I need to get the 2nd and fourth character of that string $DOMAINNAME

Any ideas?

like image 842
Mud Avatar asked Dec 14 '22 23:12

Mud


1 Answers

with bash variables, you can do this:

DOMAINNAME=abcdef
CHAR2=${DOMAINNAME:1:1}
CHAR4=${DOMAINNAME:3:1}
echo "char2=$CHAR2, char4=$CHAR4"

gives:

char2=b, char4=d

explanation

the meaning of this: ${DOMAINNAME:3:1}means: take substring starting from the character at pos 3 (0-based, so the 4th character), and length = 1 character.

like image 157
Chris Maes Avatar answered Jan 17 '23 18:01

Chris Maes