从以逗号和换行符分隔的文件中读取数组
Read array from file separated with commas and newlines
我有一个文件,每行有两个不同的词,由逗号和换行符分隔。你如何读取这个文件并将每个单词存储在一个数组中?我的代码不起作用,因为我认为只适用于 "one line" 数组。
文件示例:
每个单词由逗号和换行符分隔。
Dog,cat
shark,rabbit
mouse,bird
whale,dolphin
所需输入
"${array[0]}" = Dog
"${array[1]}" = cat
"${array[2]}" = shark
"${array[3]}" = rabbit
"${array[4]}" = mouse
"${array[5]}" = bird
"${array[6]}" = whale
"${array[7]}" = dolphin
我的代码:
input=$(cat "/path/source_file")
IFS=',' read -r -a array <<< "$input"
IFS=$'\n,' read -d '' -ra array < file
关键是用IFS
告诉read
把整个输入)-d ''
)分割成数组元素(-a
;-r
确保\n
和 ,
个字符。
为简单起见,我使用 file
表示您的输入文件,并通过标准输入 直接 作为 read
的输入(<
).
如果您确实需要先将整个文件读入 shell 变量,以下形式在 Bash 中效率稍高(但不符合 POSIX ):
input=$(< "/path/source_file")
输入格式:
从第 1 行读取 inarr1,数组元素之间用 (,) 逗号分隔。
从第 2 行读取数组元素以逗号 (,) 分隔的 inarr2。
从标准输入流读取输入
输出格式:
我有一个文件,每行有两个不同的词,由逗号和换行符分隔。你如何读取这个文件并将每个单词存储在一个数组中?我的代码不起作用,因为我认为只适用于 "one line" 数组。
文件示例:
每个单词由逗号和换行符分隔。
Dog,cat
shark,rabbit
mouse,bird
whale,dolphin
所需输入
"${array[0]}" = Dog
"${array[1]}" = cat
"${array[2]}" = shark
"${array[3]}" = rabbit
"${array[4]}" = mouse
"${array[5]}" = bird
"${array[6]}" = whale
"${array[7]}" = dolphin
我的代码:
input=$(cat "/path/source_file")
IFS=',' read -r -a array <<< "$input"
IFS=$'\n,' read -d '' -ra array < file
关键是用IFS
告诉read
把整个输入)-d ''
)分割成数组元素(-a
;-r
确保\n
和 ,
个字符。
为简单起见,我使用 file
表示您的输入文件,并通过标准输入 直接 作为 read
的输入(<
).
如果您确实需要先将整个文件读入 shell 变量,以下形式在 Bash 中效率稍高(但不符合 POSIX ):
input=$(< "/path/source_file")
输入格式:
从第 1 行读取 inarr1,数组元素之间用 (,) 逗号分隔。
从第 2 行读取数组元素以逗号 (,) 分隔的 inarr2。
从标准输入流读取输入
输出格式: