純粋な GAWK ソリューションは次のとおりです。
{ # Split on double quotes to handle lines like "this, this, or this".
printf("LINE: '%s'\nFIELDS:", $0)
n = split($0,q,/"/)
f = 0
}
n == 1 { # If n is 1, there are no double quotes on the line.
n = split($0,c,/,/)
for (i = 1; i <= n; i++) {
printf(" %d='%s'", i, c[i])
}
printf("\n")
next
}
{ # There are "strings"; the EVEN entries in q are the quoted strings.
for (i = 1; i <= n; i++) {
if (0 == and(i,1)) { # i is EVEN: This is a double-quoted string.
printf(" %d='\"%s\"'", ++f, q[i])
continue
}
if (0 == length(q[i])) { # First/last field is a quoted string.
continue
}
if (q[i] == ",") {
# First/last field empty, or comma between two quoted strings.
if (i == 1 || i == n) { # First/last field empty
printf(" %d=''", ++f)
}
continue
}
# Remove commas before/after a quoted string then split on commas.
sub(/^,/,"",q[i])
sub(/,$/,"",q[i])
m = split(q[i],cq,/,/)
for (j = 1; j <= m; j++) {
printf(" %d='%s'", ++f, cq[j])
}
}
printf("\n")
}
この入力で:
This is one,23,$9.32,Another string.
Line 2,234,$88.34,Blah blah
"This is another",763,$0.00,"trouble, or not?"
"This is, perhaps, trouble too...",763,$0.00,"trouble, or not?"
2,"This is, perhaps, trouble too...",763,"trouble, or not?"
3,,"number, number","well?"
,,,
"1,one","2,two","3,three","4,four"
",commas,","no commas",",,,,,",
,"Fields 1 and 4 are empty","But 2 and 3 are not",
次の出力が生成されます。
LINE: 'This is one,23,$9.32,Another string.'
FIELDS: 1='This is one' 2='23' 3='$9.32' 4='Another string.'
LINE: 'Line 2,234,$88.34,Blah blah'
FIELDS: 1='Line 2' 2='234' 3='$88.34' 4='Blah blah'
LINE: '"This is another",763,$0.00,"trouble, or not?"'
FIELDS: 1='"This is another"' 2='763' 3='$0.00' 4='"trouble, or not?"'
LINE: '"This is, perhaps, trouble too...",763,$0.00,"trouble, or not?"'
FIELDS: 1='"This is, perhaps, trouble too..."' 2='763' 3='$0.00' 4='"trouble, or not?"'
LINE: '2,"This is, perhaps, trouble too...",763,"trouble, or not?"'
FIELDS: 1='2' 2='"This is, perhaps, trouble too..."' 3='763' 4='"trouble, or not?"'
LINE: '3,,"number, number","well?"'
FIELDS: 1='3' 2='' 3='"number, number"' 4='"well?"'
LINE: ',,,'
FIELDS: 1='' 2='' 3='' 4=''
LINE: '"1,one","2,two","3,three","4,four"'
FIELDS: 1='"1,one"' 2='"2,two"' 3='"3,three"' 4='"4,four"'
LINE: '",commas,","no commas",",,,,,",'
FIELDS: 1='",commas,"' 2='"no commas"' 3='",,,,,"' 4=''
LINE: ',"Fields 1 and 4 are empty","But 2 and 3 are not",'
FIELDS: 1='' 2='"Fields 1 and 4 are empty"' 3='"But 2 and 3 are not"' 4=''