5

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?

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am generating the urls from a python script, so I can change it and make it print several lines. How can I get them on an array? could you update that also please?
I ended up using a multiline file, but the array works great too.
5

You should use something like this

declare -a a=( $str )
n=${#a[*]} # number of elements

Comments

4

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

Comments

0

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="firsturl.com/123416 secondurl.com/634214"
count_params $str

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.