Bash脚本,如何删除尾随子串,不区分大小写?

时间:2010-12-01 22:40:13

标签: bash string case-insensitive

我正在修改读取用户电子邮件的脚本。它非常简单,太简单了。

echo -n "Please enter your example.com email address: "
read email
email=${email%%@example.com} # removes trailing @example.com from email
echo "email is $email"

这样可行,但仅适用于小写@ example.com。我怎么能修改它来删除尾随的@ example.com,不区分大小写?

6 个答案:

答案 0 :(得分:5)

如果你有bash 4:

email=${email,,}
email=${email%%@example.com}

否则,也许只使用tr:

email=$(echo "${email}" | tr "A-Z" "a-z")
email=${email%%@example.com}

<强>更新

如果您只想剥离主机(任何主机),那么这可能就是您想要的:

email=${email%%@*}

答案 1 :(得分:3)

对于Bash 3.2及更高版本:

shopt -s nocasematch
email='JoHnDoE@eXaMpLe.CoM'
pattern='^(.*)@example.com$'
[[ $email =~ $pattern ]]
email=${BASH_REMATCH[1]}    # result: JoHnDoE

答案 2 :(得分:2)

这是另一个(虽然有点冗长)接受它:

email='JoHnDoE@eXaMpLe.CoM'
email=${email%%@[Ee][Xx][Aa][Mm][Pp][Ll][Ee].[Cc][Oo][Mm]}
echo "email is $email"

答案 3 :(得分:1)

使用sed怎么样?

email="$(sed 's|@example\.com$||i' <<<"$email")"

请注意sed substitution命令中的'i'标志,该命令请求不区分大小写的匹配。

答案 4 :(得分:0)

echo -n "Please enter your example.com email address: "
read _email
_email=$(echo $_email | awk 'BEGIN{ FS="@" }  {print $1}')
echo $_email

对于转发电子邮件到小写,您可以使用声明,例如

声明-l email = $ email

答案 5 :(得分:0)

使用不区分大小写的正则表达式匹配:

echo -n "Please enter your example.com email address: "
read email
shopt -s nocasematch # Makes comparisons case insensitive
if [[ $email =~ example.com$ ]]; then
    domain=${BASH_REMATCH[0]}
    echo "email is ${email%%@$domain}"
fi

或者,您可以根据其长度截断一个字符串(仅当您知道用户正确输入域时才有意义):

echo -n "Please enter your example.com email address: "
read email
domain=example.com
email_length=${#email}
domain_length=${#domain}
name_length=$(($email_length-$domain_length-1))
email=${email:0:$name_length} # removes trailing @example.com from email
echo "email is $email"