Results 1 to 6 of 6
  1. #1
    Join Date
    Jul 2006
    Posts
    115

    Unanswered: count pattern occurrences in a line

    pls advise how to count pattern occurrences in a line.

    #:#1#:#2#:#3#:#4
    => no of #:# : 4

    i try
    echo "#:#1#:#2#:#3#:#4" |sed 's/#:#/\n/g ' |grep -c ...

    but doesnt work in solaris

    thx

  2. #2
    Join Date
    Jun 2007
    Location
    London
    Posts
    2,527
    This should work:
    Code:
    echo "#:#1#:#2#:#3#:#4" | awk '{ split($0,a,"#:#"); print length(a) - 1 }'

  3. #3
    Join Date
    Jul 2006
    Posts
    115
    good good good ... thx mike_bike_kite again ... but u seem love to use awk a lot ...

  4. #4
    Join Date
    Jun 2007
    Location
    London
    Posts
    2,527
    whatever works

  5. #5
    Join Date
    Apr 2004
    Location
    Boston, MA
    Posts
    325
    Quote Originally Posted by ymho
    pls advise how to count pattern occurrences in a line.

    #:#1#:#2#:#3#:#4
    => no of #:# : 4
    Actually there're 5 (five) fields in this record: '', '1', '2', '3', '4'

    but if don't want to count the first 'empty' field, you can always substract '1':
    Code:
     echo "#:#1#:#2#:#3#:#4" | awk -F'#:#' '{ print NF-1}'
    vlad
    +-----------------------+
    | #include <disclaimer.h> |
    +-----------------------+

  6. #6
    Join Date
    Jun 2007
    Location
    London
    Posts
    2,527
    Yep - that's a better way of doing it

Posting Permissions

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