简体   繁体   中英

Selecting strings and characters from variables in bash

I'm reading text in from a txt file, and I have to create a username from an email. The email address is in a single variable. The username must be the first letter of the users first name, and their entire last name. For example, joe.bloggs@gmail.com's username would be "jbloggs"

How do I select the first letter from the first name, then the entire last name, and concatenante them into 1 variable? I think I use the cut method but I'm unsure how to do it.

Thanks

mailbox=${EMAIL%@*}
echo ${mailbox:0:1}${mailbox#*.}

The first line removes the domain. The second grabs the initial and then removes the whole first name to leave the last.

echo "joe.bloggs@gmail.com" |sed -r 's/(^.).*\.(.*)@.*/\1\2/g'
jbloggs

Explanation:
Here the First character is captured in first () and last name is captured in second () . Later they are called as \\1 and \\2 . Check backreferencing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM