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..
我将如何迭代它,并将每个url解析为数组实例..
i.e.
array[0]
array[1]
array[2]
array[3]
thanks guys
2 个解决方案
#1
4
Pure bash way:
纯粹的bash方式:
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]}
# ...
#2
0
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.
该数组将有4个元素,而不是3. URL不能包含空格,因此这不是问题。对于一般情况,bash 4提供了mapfile命令,该命令确保每行为数组提供单个元素。
mapfile array < file.txt
is a one-step replacement for the following loop:
是以下循环的一步替代:
while IFS= read -r line; do
array+=( "$line" )
done < file.txt
#1
4
Pure bash way:
纯粹的bash方式:
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]}
# ...
#2
0
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.
该数组将有4个元素,而不是3. URL不能包含空格,因此这不是问题。对于一般情况,bash 4提供了mapfile命令,该命令确保每行为数组提供单个元素。
mapfile array < file.txt
is a one-step replacement for the following loop:
是以下循环的一步替代:
while IFS= read -r line; do
array+=( "$line" )
done < file.txt