我有这个功能,工作正常,但我想用bash重写它。问题是,我对bash中可用的内容知之甚少。
#!/usr/bin/python
def parse_svnversion(value):
"""split the output of svnversion into its three components
given a string that looks like the output of the command
svnversion, returns the 3-tuple (low, high, flags)
>>> parse_svnversion('1024')
(1024, 1024, '')
>>> parse_svnversion('1024:2000')
(1024, 2000, '')
>>> parse_svnversion('1024M')
(1024, 1024, 'M')
>>> parse_svnversion('1024:2000MP')
(1024, 2000, 'MP')
"""
values = filter(lambda x: x.isdigit() or x==':', value).split(':')
return int(values[0]), int(values[-1]), filter(str.isalpha, value)
if __name__ == '__main__':
import doctest
doctest.testmod()
我想要的是一个类似的小bash函数,我可以调用它,并设置一些东西(三个变量?一个数组?),我可以使用它。如果它是一个数组,我真的希望它是固定大小(3)。
答案 0 :(得分:4)
这会创建一个名为“tuple”的数组,其中包含三个元素:
[[ $(svnversion .) =~ ([0-9]+):*([0-9]*)([A-Z]*) ]]
tuple[0]=${BASH_REMATCH[1]}
tuple[1]=${BASH_REMATCH[2]:-${tuple[0]}}
tuple[2]=${BASH_REMATCH[3]:-''}
需要Bash 3.2或更高版本。它可以在Bash> = 3和< 3.2。不能移植到Bourne shell,虽然它可以适用于Korn shell或Z shell。
ksh
使用.sh.match
数组变量,例如:${.sh.match[1]}
zsh
使用match
数组变量,例如:${match[1]}
或者您可以
setopt bashrematch ksharrays
让它与Bash版本完全一样。
支架替换应该对所有三个都相同。
答案 1 :(得分:1)
你可以使用这个子程序
parsesvn(){
toparse="$1"
num=${toparse%%[A-Z]*}
alpha=${toparse##*[0-9]}
IFS=":"
set -- $num
for i in $@
do
printf "%s " $i
done
if [ ! -z "$alpha" ];then
printf "%s" "$alpha"
fi
}
# main #
var=$(parsesvn "1024:2000")
set -- $var
if [ "$1" -lt "$2" ];then
echo "ok"
greater=$2
else
echo "LHS: $1 greater than RHS: $2"
fi
echo "greater is $greater"
答案 2 :(得分:0)
以下解决方案将值存储到数组arr []中,以尽可能地匹配原始元组。在if-else-fi
块后,您可以使用arr [0],arr [1]和arr [2]执行任何操作。我试图尽可能地匹配你的帖子(和评论)。此外,我冒昧地向STDERR发送警告和通知消息,而不是STDOUT认为您可能想要将它们分开。
#!/bin/bash
parse_svnversion()
{
if [[ "$1" = *:* ]]; then
arr[0]=${1%:*}
arr[2]=${1//[0-9:]/}
tmp_arr[1]=${1#*:}
arr[1]=${tmp_arr[1]//${arr[2]}/}
else
arr[2]=${1//[0-9:]/}
arr[0]=${1//${arr[2]}/}
arr[1]=${arr[0]}
fi
echo ${arr[@]}
head_rev=$( (( ${arr[0]} > ${arr[1]} )) && echo ${arr[0]} || echo ${arr[1]} )
echo "Notice: head revision is $head_rev" >&2
if (( ${arr[1]} < ${arr[0]} )); then
echo "Warning: you're working with mixed revisions" >&2
fi
if [[ -n ${arr[2]} ]]; then
echo "Warning: there are flags" >&2
fi
}
parse_svnversion "1024"
parse_svnversion "1024:2000"
parse_svnversion "1024M"
parse_svnversion "1024:2000MP"
parse_svnversion "2000:1024M"
$ ./svn_split.sh 2> /dev/null 1024 1024 1024 2000 1024 1024 M 1024 2000 MP 2000 1024 M
$ ./svn_split.sh 1024 1024 Notice: head revision is 1024 1024 2000 Notice: head revision is 2000 1024 1024 M Notice: head revision is 1024 Warning: there are flags 1024 2000 MP Notice: head revision is 2000 Warning: there are flags 2000 1024 M Notice: head revision is 2000 Warning: you're working with mixed revisions Warning: there are flags