Unix administration - number of occurences of a string in a line

This is Interesting: Free IT Magazines  
Home > Archive > Unix administration > November 2005 > number of occurences of a string in a line





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author number of occurences of a string in a line
kr.badrinath@gmail.com

2005-11-14, 5:57 pm

Could you please help me out to find number of occurences of a string
in a line.

input file:
123siva456siva789siva
222siva555siva
888siva 999siva

expected output for word siva:

line1:3occurences
line2:2occurences
line3:3occurences

Thx,
Badri

Dave Hinz

2005-11-14, 5:57 pm

On 14 Nov 2005 11:44:24 -0800, kr.badrinath@gmail.com <kr.badrinath@gmail.com> wrote:
> Could you please help me out to find number of occurences of a string
> in a line.


When is your homework due, please, and should we expect to see _all_ of
your assignments? If so, please post them in a batch for the
convenience of the people who feel like doing your work for you.


Loki Harfagr

2005-11-19, 5:51 pm

Le Mon, 14 Nov 2005 11:44:24 -0800, kr.badrinath a écrit_:

> Could you please help me out to find number of occurences of a string in
> a line.
>
> input file:
> 123siva456siva789siva
> 222siva555siva
> 888siva 999siva
>
> expected output for word siva:
>
> line1:3occurences
> line2:2occurences
> line3:3occurences


Are you really sure you actually count 3 occurences
of 'siva' in line 3 ?

>
> Thx,
> Badri


Anyway, if you want to try this, it'd help you a bit in
reading a few pages as to explain to your trainor how
you made it up :

$ awk 'NF{print NF-1}' FS='siva' yourinputfile

This, on a little bit extended test file gives :

$ cat MISCFILES/countwordsinline.txt
123siva456siva789siva
222siva555siva
888siva 999siva
siva
888siva 999siva111visa
888siva 999siva111visa333

$ gawk 'NF{print NF-1}' FS='siva' MISCFILES/countwordsinline.txt
3
2
2
1
2
2

The exercise of printing out a 0 when necessary is left as
a bait for reading some pages ;-)
Chris F.A. Johnson

2005-11-19, 5:51 pm

On 2005-11-14, kr.badrinath@gmail.com wrote:
> Could you please help me out to find number of occurences of a string
> in a line.
>
> input file:
> 123siva456siva789siva
> 222siva555siva
> 888siva 999siva
>
> expected output for word siva:
>
> line1:3occurences
> line2:2occurences
> line3:3occurences


awk '{ l = $0
r = gsub("siva","")
printf "line %d: %d occurrences\n", NR, r
}'

--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com