Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2003
    Posts
    2

    Unanswered: count the number of characters in a string?

    I have a string ie. x="123 44 55 ffffccc xxx"
    how do I go about counting just the characters, not the whitespace?

    Thanks.

  2. #2
    Join Date
    Jul 2003
    Location
    Edinburgh
    Posts
    35

    Re: count the number of characters in a string?

    Originally posted by Racer_X
    I have a string ie. x="123 44 55 ffffccc xxx"
    how do I go about counting just the characters, not the whitespace?

    Thanks.
    Use a pipeline.

    Use tr to remove the whitespace

    use wc to count the remaining characters

  3. #3
    Join Date
    Oct 2003
    Location
    Germany
    Posts
    138
    I do it like this :
    the char "@" does not occur in your string. Othewise use in FS another char which surely never can occur in your string.
    ##################### count the chars in string
    x="123 44 55 ffffccc xxx"
    chars=`echo $x | awk ' BEGIN { FS="@"}
    {
    x=length($1)
    y=0
    while ( y != x)
    {
    y=y+1
    if (substr($1, y, 1 ) != " " )
    {
    chars=chars+1
    }
    }
    } END {
    print chars
    }'`
    echo "numbers of chars in variabe x "$chars
    Last edited by fla5do; 01-13-04 at 16:57.
    Greetings from germany
    Peter F.

  4. #4
    Join Date
    Jul 2003
    Location
    Edinburgh
    Posts
    35
    Well, it looks like one cannot use /usr/bin/tr to delete characters. Also, echo appends a newline by default. So my updated version is:

    echo -n $x | sed 's/ //g' | wc -c

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •