Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: split by comma with special characters

Tags:

bash

I have a list that is comma delimited like so...

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

I'm trying to loop over these lines and populate variables with the 3 columns in each row. My script works when the data has no spaces, ampersands, or apostrophes. When it does have those then it doesn't work right. 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 point out how I can get this script to work with my list I would greatly appreciate it!

EV

like image 307
exvance Avatar asked Jul 18 '13 21:07

exvance


2 Answers

while IFS=, read field1 field2 field3
do
  echo $field1
  echo $field2
  echo $field3
done < list
like image 75
Sean Bright Avatar answered Oct 10 '22 11:10

Sean Bright


Can you use awk?

awk -F',' '{print "Field1: " $1 "\nField2: " $2 "\nField3: " $3}'
like image 44
David Wilkins Avatar answered Oct 10 '22 11:10

David Wilkins