1

I have the following simple ksh code:

 MY_LIST=first,second,third
 NUM_IN_LIST=` echo $MY_LIST | sed s"/,/ /g" | wc -w `
 print $NUM_IN_LIST
 3
 [[ $NUM_IN_LIST = 3 ]] && print match

 but I dont get the match print -:(

maybe because some spaces?

can I get some other suggestion to count and print the words in $MY_LIST ? (after remove the "," seperator)

jennifer
  • 1,117

2 Answers2

1

Your code should work, but only if $MY_LIST doesn't contain any of various special characters:

  • echo $MY_LIST should be printf %s "$MY_LIST" or print -r -- "$MY_LIST". The lack of quotes tells the shell to expant globbing characters \\*?[. It also tells the shell to split words at spaces, although that wouldn't matter here except for the next problem.
  • Using echo additionally causes interpretation of backslashes and a leading - in some circumstances.
  • `sed s"/,/ /g" makes both commas and spaces word separators.

An additional issue, explaining why your final test doesn't work, is that wc -w produces output with leading spaces, which are captured in $NUM_IN_LIST. print $NUM_IN_LIST performs word splitting on $NUM_IN_LIST, so it ends up just printing the digits; do print "$NUM_IN_LIST" to see the difference. The [[ … ]] construct inhibits word splitting, and = is a string comparison operator, so you are correctly told that ' 3' is not the same thing as '3'. [[ $NUM_IN_LIST -eq 3 ]] or [ $NUM_IN_LIST = 3 ] would have been true (but neither is a real solution, they're just limited workarounds).


A pure ksh way to show the number of comma-separated fields is

commas=${MY_LIST//[!,]/}
NUM_IN_LIST=${#commas}

If anyone needs a POSIX sh solution, replace the first line by commas=$(printf %s "$MY_LIST" | tr -dc ,).

0

Your example works for me.

Here's an alternative:

MY_LIST=first,second,third
saveIFS=$IFS
IFS=','
array=($MY_LIST)
IFS=$saveIFS
NUM_IN_LIST=${#array[@]}
print $NUM_IN_LIST
[[ $NUM_IN_LIST = 3 ]] && print match