使用 Bash 将文件内容提取到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20294918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract file contents into array using Bash
提问by JafarAlali92
How to extract a file content into array in Bash line by line. Each line is set to an element.
如何将文件内容逐行提取到 Bash 中的数组中。每行都设置为一个元素。
I've tried this:
我试过这个:
declare -a array=(`cat "file name"`)
but it didn't work, it extracts the whole lines into [0]
index element
但它没有用,它将整行提取到[0]
索引元素中
回答by H?kon H?gland
For bash version 4, you can use:
对于 bash 版本 4,您可以使用:
readarray -t array < file.txt
回答by Junior Dussouillez
You can use a loop to read each line of your file and put it into the array
您可以使用循环读取文件的每一行并将其放入数组
# Read the file in parameter and fill the array named "array"
getArray() {
array=() # Create array
while IFS= read -r line # Read a line
do
array+=("$line") # Append line to the array
done < ""
}
getArray "file.txt"
How to use your array :
如何使用你的数组:
# Print the file (print each element of the array)
getArray "file.txt"
for e in "${array[@]}"
do
echo "$e"
done
回答by potong
This might work for you (Bash):
这可能对你有用(Bash):
OIFS="$IFS"; IFS=$'\n'; array=($(<file)); IFS="$OIFS"
Copy $IFS
, set $IFS
to newline, slurp file into array and reset $IFS
back again.
Copy $IFS
,设置$IFS
为换行符,将文件放入数组并$IFS
再次重置。