array-stuff

来自「UNIX下SH的实现源码」· 代码 · 共 104 行

TXT
104
字号
# usage: reverse arraynamereverse(){	local -a R	local -i i	local rlen temp	# make r a copy of the array whose name is passed as an arg	eval R=\( \"\$\{$1\[@\]\}\" \)	# reverse R	rlen=${#R[@]}	for ((i=0; i < rlen/2; i++ ))	do		temp=${R[i]}		R[i]=${R[rlen-i-1]}		R[rlen-i-1]=$temp	done	# and assign R back to array whose name is passed as an arg	eval $1=\( \"\$\{R\[@\]\}\" \)}A=(1 2 3 4 5 6 7)echo "${A[@]}"reverse Aecho "${A[@]}"reverse Aecho "${A[@]}"# unset last element of Aalen=${#A[@]}unset A[$alen-1]echo "${A[@]}"# ashift -- like shift, but for arraysashift(){	local -a R	local n	case $# in	1)	n=1 ;;	2)	n=$2 ;;	*)	echo "$FUNCNAME: usage: $FUNCNAME array [count]" >&2		exit 2;;	esac	# make r a copy of the array whose name is passed as an arg	eval R=\( \"\$\{$1\[@\]\}\" \)	# shift R	R=( "${R[@]:$n}" )	# and assign R back to array whose name is passed as an arg	eval $1=\( \"\$\{R\[@\]\}\" \)}ashift A 2echo "${A[@]}"ashift Aecho "${A[@]}"ashift A 7echo "${A[@]}"# Sort the members of the array whose name is passed as the first non-option# arg.  If -u is the first arg, remove duplicate array members.array_sort(){	local -a R	local u	case "$1" in	-u)	u=-u ; shift ;;	esac	if [ $# -eq 0 ]; then		echo "array_sort: argument expected" >&2		return 1	fi	# make r a copy of the array whose name is passed as an arg	eval R=\( \"\$\{$1\[@\]\}\" \)	# sort R	R=( $( printf "%s\n" "${A[@]}" | sort $u) )	# and assign R back to array whose name is passed as an arg	eval $1=\( \"\$\{R\[@\]\}\" \)	return 0}A=(3 1 4 1 5 9 2 6 5 3 2)array_sort Aecho "${A[@]}"A=(3 1 4 1 5 9 2 6 5 3 2)array_sort -u Aecho "${A[@]}"

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?