据我了解,在编写 Unix shell 程序时,您可以像带有 for 循环的列表一样遍历字符串。这是否意味着您也可以通过索引访问字符串的元素?
例如:
foo="fruit vegetable bread"
我怎样才能访问这句话的第一个单词?我尝试使用像基于 C 的语言这样的括号无济于事,而且我在网上阅读的解决方案需要正则表达式,我现在想避免使用它。
作为参数传递$foo
给函数。比你可以使用$1
,$2
等等来访问函数中的相应单词。
function try {
echo $1
}
a="one two three"
try $a
编辑:另一个更好的版本是:
a="one two three"
b=( $a )
echo ${b[0]}
编辑(2):看看这个线程。
使用数组是最好的解决方案。
这是使用间接变量的一种棘手方法
get() { local idx=${!#}; echo "${!idx}"; }
foo="one two three"
get $foo 1 # one
get $foo 2 # two
get $foo 3 # three
笔记:
$#
是给函数的参数数量(在所有这些情况下都是 4 个)${!#}
是最后一个参数的值${!idx}
是第'th 参数的值idx
$foo
,以便 shell 可以将字符串拆分为单词。通过一些错误检查:
get() {
local idx=${!#}
if (( $idx < 1 || $idx >= $# )); then
echo "index out of bounds" >&2
return 1
fi
echo "${!idx}"
}
请不要实际使用此功能。使用数组。