geotheory
geotheory

Reputation: 23660

Delimiting string in bash ignoring delimiters in quotes

I don't suppose there's a way to get this command to ignore the comma within quotes (between the 'three's)?

$ echo 'one,two,"three,three",four' | { IFS=',' read -a array; echo ${#array[@]}; }
5

Nb. echo ${#array[@]} reports array length..

Upvotes: 1

Views: 294

Answers (2)

anubhava
anubhava

Reputation: 785156

Using FPAT in gnu-awk you can do it:

str='one,two,"three,three",four'

awk -v FPAT='"[^"]*"|[^,]*' '{
   print "# of columns: " NF; for(i=1; i<=NF; i++) print "Field #", i, ":", $i
}' <<< "$str"

Output:

# of columns: 4
Field # 1 : one
Field # 2 : two
Field # 3 : "three,three"
Field # 4 : four

Upvotes: 3

Guido
Guido

Reputation: 926

Escape the comma:

echo 'one,two,"three\,three",four'

Result:

$ echo 'one,two,"three\,three",four' | { IFS=',' read -a array; echo ${#array[@]} ${array[2]}; }
4 "three,three"

Upvotes: 1

Related Questions