Home > Net >  How can you split a string in bash script by starting at a certain char and ending at another
How can you split a string in bash script by starting at a certain char and ending at another

Time:09-14

i have an email address and i am wanting to split the email in the first letter of the firstname and full last name and put them in a place holder. eg: [email protected]

x = f 
y = lastname

I did use try firstCharacter=${email:0:1} to get the first char but am not sure how to get the last name.

Full code here

#!/bin/bash

file="users.csv.1"
Count=0

while IFS=";"; read email birthDate group sharedFolder
do
        echo -e "Email: $email"
        firstCharacter=${email:0:1}
        echo $firstCharacter
        IFS="."
        read -ra
        echo -e "Birth Date: $birthDate"
        echo -e "Group: $group"
        echo -e "shared Folder: $sharedFolder\n"

done < "$file"

CodePudding user response:

local_part=${email%%@*}     # remove trailing `@*` (glob-style pattern)
last_name=${local_part##*.} # remove the leading `*.` from above

CodePudding user response:

One idea using parameter expansion/substitution:

$ email='[email protected]'
$ lastName="${email//@*}"                   # strip off domain (ie, everything from @ to end of string)
$ lastName="${lastName//*.}"                # strip off everything from start of string up to to and including last period; should address email addresses like 'firstname.mi.lastname'
$ typeset -p lastName
declare -- lastName="lastname"
  • Related