Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script - check length when splitting string to array

Tags:

linux

bash

shell

I am using a bash script and I am trying to split a string with urls inside for example:

str=firsturl.com/123416 secondurl.com/634214

So these URLs are separated by spaces, I already used the IFS command to split the string and it is working great, I can iterate trough the two URLs with:

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 str example it should return 2, but using this:

${#str[@]}

return the length of the string (40 for the current example), I mean the number of characters, when I need to get 2.

Also iterating with a counter won't work, because I need the number of elements before iterating the array.

Any suggestions?

like image 701
eLRuLL Avatar asked Jun 28 '13 03:06

eLRuLL


3 Answers

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 read loop:

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.

like image 80
that other guy Avatar answered Oct 05 '22 23:10

that other guy


You should use something like this

declare -a a=( $str )
n=${#a[*]} # number of elements
like image 33
Diego Torres Milano Avatar answered Oct 06 '22 01:10

Diego Torres Milano


Several ways:

$ str="firsturl.com/123416 secondurl.com/634214"

bash array:

$ while read -a ary; do echo ${#ary[@]}; done <<< "$str"
2

awk:

$ awk '{print NF}' <<< "$str"
2

*nix utlity:

$ printf "%s\n" $(printf "$str" | wc -w)
2

bash without array:

$ set -- $str
$ echo ${#@}
2
like image 21
jaypal singh Avatar answered Oct 06 '22 00:10

jaypal singh