Issue
I have a file that has two different words per line, delimited by a comma and a line break. How can you read this file and store every word in an array? My code doesn't work because I think only works for "one line" array.
File Sample:
Each word is separated by a comma and a line break.
Dog,cat
shark,rabbit
mouse,bird
whale,dolphin
Desired input
"${array[0]}" = Dog
"${array[1]}" = cat
"${array[2]}" = shark
"${array[3]}" = rabbit
"${array[4]}" = mouse
"${array[5]}" = bird
"${array[6]}" = whale
"${array[7]}" = dolphin
My Code:
input=$(cat "/path/source_file")
IFS=',' read -r -a array <<< "$input"
Solution
IFS=$'\n,' read -d '' -ra array < file
The key is to use IFS
to tell read
to split the entire input) -d ''
) into array elements (-a
; -r
ensures unmodified reading) by both \n
and ,
characters.
For simplicity, I've used file
to represent your input file and used it directly as input to read
via stdin (<
).
If you do have a need to read the entire file into a shell variable first, the following form is slightly more efficient in Bash (but is not POSIX-compliant):
input=$(< "/path/source_file")
Answered By - mklement0 Answer Checked By - Katrina (WPSolving Volunteer)