Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following simple ksh code:

 NUM_IN_LIST=` echo $MY_LIST | sed s"/,/ /g" | wc -w `
 print $NUM_IN_LIST
 [[ $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)

share|improve this question
up vote 0 down vote accepted

Your example works for me.

Here's an alternative:

print $NUM_IN_LIST
[[ $NUM_IN_LIST = 3 ]] && print match
share|improve this answer
another example is to use the awk '{print NF}' to count the elements in MY_LIST – jennifer Oct 5 '10 at 10:33
You need set -f before the unquoted $MY_LIST, in case the string contains globbing characters. But using IFS is more complicated that it needs to be in ksh. – Gilles Oct 5 '10 at 21:40

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


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

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .