Bash: comma separated with special characters

I have a comma separated list, so ...

00:00:00:00:00:00,Bob Laptop,11111111111111111 00:00:00:00:00:00,Mom & Dad Computer,22222222222222222 00:00:00:00:00:00,Kitchen,33333333333333333 

I am trying to iterate over these rows and populate the variables with three columns in each row. My script works when data has no spaces, ampersands or apostrophes. When he has one, then it does not work correctly. Here is my script:

  for line in $(cat list) do arr=(`echo $line | tr "," "\n"`) echo "Field1: ${arr[0]}" echo "Field2: ${arr[1]}" echo "Field3: ${arr[2]}" done 

If one of you bash gurus can indicate how I can get this script to work with my list, I would really appreciate it!

E.V.

+6
source share
3 answers
 while IFS=, read field1 field2 field3 do echo $field1 echo $field2 echo $field3 done < list 
+5
source

Can you use awk?

 awk -F',' '{print "Field1: " $1 "\nField2: " $2 "\nField3: " $3}' 
+3
source

Do not read lines with a for loop. Use read instead

 while IFS=, read -r -a line; do printf "%s\n" "${line[0]}" "${line[1]}" "${line[2]}"; done < list 

Or using array partitioning

 while IFS=, read -r -a line; do printf "%s\n" "${line[@]:0:3}"; done < list 
+3
source

Source: https://habr.com/ru/post/949783/


All Articles