bash Shell 脚本 - 将字符串拆分为数组时检查长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17356831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shell script - check length when splitting string to array
提问by eLRuLL
I am using a bash script and I am trying to split a string with urls inside for example:
我正在使用 bash 脚本,并且我正在尝试拆分包含 url 的字符串,例如:
str=firsturl.com/123416 secondurl.com/634214
So these URLs are separated by spaces, I already used the IFScommand to split the string and it is working great, I can iterate trough the two URLs with:
所以这些 URL 用空格分隔,我已经使用IFS命令来分割字符串并且它工作得很好,我可以通过以下两个 URL 迭代:
for url in $str; do
#some stuff
done
But my problem is that I need to get how many items this splitting has, so for the strexample it should return 2, but using this:
但是我的问题是我需要获得这个拆分有多少个项目,所以对于这个str例子它应该返回 2,但是使用这个:
${#str[@]}
return the length of the string (40for the current example), I mean the number of characters, when I need to get 2.
返回字符串的长度(40对于当前示例),我的意思是字符数,当我需要获取2.
Also iterating with a counter won't work, because I need the number of elements before iterating the array.
用计数器迭代也不起作用,因为在迭代数组之前我需要元素的数量。
Any suggestions?
有什么建议?
采纳答案by that other guy
Split the string up into an array and use that instead:
将字符串拆分成一个数组并使用它:
str="firsturl.com/123416 secondurl.com/634214"
array=( $str )
echo "Number of elements: ${#array[@]}"
for item in "${array[@]}"
do
echo "$item"
done
You should never have a space separated list of strings though. If you're getting them line by line from some other command, you can use a while readloop:
但是,您永远不应该有空格分隔的字符串列表。如果您从其他命令逐行获取它们,则可以使用while read循环:
while IFS='' read -r url
do
array+=( "$url" )
done
For properly encoded URLs, this probably won't make much of a difference, but in general, this will prevent glob expansion and some whitespace issues, and it's the canonical format that other commands (like wget -i) works with.
对于正确编码的 URL,这可能不会有太大区别,但总的来说,这将防止 glob 扩展和一些空白问题,并且它是其他命令(如wget -i)使用的规范格式。
回答by Diego Torres Milano
You should use something like this
你应该使用这样的东西
declare -a a=( $str )
n=${#a[*]} # number of elements
回答by jaypal singh
Several ways:
几种方式:
$ str="firsturl.com/123416 secondurl.com/634214"
bash array:
bash数组:
$ while read -a ary; do echo ${#ary[@]}; done <<< "$str"
2
awk:
awk:
$ awk '{print NF}' <<< "$str"
2
*nix utlity:
*nix 实用程序:
$ printf "%s\n" $(printf "$str" | wc -w)
2
bash without array:
没有数组的 bash:
$ set -- $str
$ echo ${#@}
2
回答by dougEfresh
If you create a function that will echo $* then that should provide the number of items to split.
如果您创建一个将回显 $* 的函数,那么它应该提供要拆分的项目数。
count_params () { echo $#; }
Then passing $str to this function will give you the result
然后将 $str 传递给这个函数会给你结果
str="firsturl.com/123416 secondurl.com/634214"
count_params $str

