2

i have a text file with many urls

www.example1.com
www.example2.com
www.example3.com
www.example4.com

How would i go about iterating through it, and parsing each url into an array instance..

i.e.

array[0]
array[1]
array[2]
array[3]

thanks guys

3 Answers 3

8

Pure bash way:

array=($(<inFile))

then:

# list all the elements of array
echo "${array[@]}"

# echo num of elements in array
echo ${#array[@]}

## OR loop through the above array
for i in "${array[@]}"
do
   echo $i # or do whatever with individual element of the array
done

# 1st element of array
echo ${array[0]}

# 2nd element of array
echo ${array[2]}

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

9 Comments

thought it would work, but getting Syntax error: "(" unexpected
@user2466087, this requires bash or ksh or zsh: plain sh does not do arrays
@anubhava, you should get into the habit of quoting variables: ${array[@]} and "${array[@]}" return different things.
@glennjackman so what should I do, Iam running a (.sh) script in which i have links inside a textfile.txt which need to be put in an array...?
test with array=("a b" "c d") to see the difference
|
1

One concern with ( $(< file.txt) ) is if a line in the file can contain whitespace. Consider the array produced from

a b
c
d

The array would have 4 elements, not 3. URLs cannot contain whitespace, so it is not an issue here. For the general case, bash 4 provides a mapfile command which ensures that each line provides a single element for an array.

mapfile array < file.txt

is a one-step replacement for the following loop:

while IFS= read -r line; do
    array+=( "$line" )
done < file.txt

Comments

0

If you want to have the array be in your script instead of reading a file you can use this approach.

#!/bin/bash

array=(
"www.example1.com"
"www.example2.com"
"www.example3.com"
"www.example4.com"
)

for URL in "${array[@]}"; do
    echo "$URL"
done

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.