[英]parsing urls from a text file to bash shell array
我有一個包含許多網址的文本文件
www.example1.com
www.example2.com
www.example3.com
www.example4.com
我 go 如何遍歷它,並將每個 url 解析為一個數組實例..
IE
array[0]
array[1]
array[2]
array[3]
多謝你們
純bash方式:
array=($(<inFile))
然后:
# 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]}
# ...
與( $(< file.txt) )
的一個問題是文件中的一行是否可以包含空格。 考慮由
a b
c
d
該數組將包含4個元素,而不是3個。URL不能包含空格,因此這里不是問題。 對於一般情況, bash
4提供了一個mapfile
命令,該命令可確保每一行為數組提供單個元素。
mapfile array < file.txt
是以下循環的單步替換:
while IFS= read -r line; do
array+=( "$line" )
done < file.txt
如果你想讓數組在你的腳本中而不是讀取文件,你可以使用這種方法。
#!/bin/bash
array=(
"www.example1.com"
"www.example2.com"
"www.example3.com"
"www.example4.com"
)
for URL in "${array[@]}"; do
echo "$URL"
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.