在shell中,以点分隔符分割字符串的一部分 [英] In shell, split a portion of a string with dot as delimiter
问题描述
我是Shell脚本的新手,请帮忙满足以下要求,谢谢.
I am new to shell scripting, can you please help with below requirement, thanks.
$AU_NAME=AU_MSM3-3.7-00.01.02.03
#separate the string after last "-", with "." as delimiter
#that is, separate "00.01.02.03" and print/save as below.
major=00
minor=01
micro=02
build=03
推荐答案
首先,请注意,在外壳程序中分配参数时,请勿使用$
.您的第一行应该是这样:
First, note that you don't use $
when assigning to a parameter in the shell. Your first line should be just this:
AU_NAME=AU_MSM3-3.7-00.01.02.03
一旦有了,就可以做这样的事情:
Once you have that, then you can do something like this:
IFS=. read major minor micro build <<EOF
${AU_NAME##*-}
EOF
其中,##*-
将从字符串的开头到最后一个'-'剥离所有内容,仅留下"00.01.02.03",而IFS(内部字段分隔符)变量告诉Shell将字符串分成何处字段.
where the ##*-
strips off everything from the beginning of the string through the last '-', leaving just "00.01.02.03", and the IFS (Internal Field Separator) variable tells the shell where to break the string into fields.
在bash,zsh和ksh93 +中,您可以通过将here-document缩短为here-string来将其放在一行上:
In bash, zsh, and ksh93+, you can get that onto one line by shortening the here-document to a here-string:
IFS=. read major minor micro build <<<"${AU_NAME##*-}"
更一般而言,在那些相同的shell(或任何其他具有数组的shell)中,您可以拆分为任意大小的数组,而不是单独的变量.可以在给定的shell中使用:
More generally, in those same shells (or any other shell that has arrays), you can split into an arbitrarily-sized array instead of distinct variables. This works in the given shells:
IFS=. components=(${AU_NAME##*-})
在旧版本的ksh中,您可以执行以下操作:
In older versions of ksh you can do this:
IFS=. set -A components ${AU_NAME##*-}
这使您具有等效性(zsh除外,默认情况下,zsh将元素编号为1-4而不是0-3):
That gets you this equivalence (except in zsh, which by default numbers the elements 1-4 instead of 0-3):
major=${components[0]}
minor=${components[1]}
micro=${components[2]}
build=${components[3]}
这篇关于在shell中,以点分隔符分割字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!