Link to home
Start Free TrialLog in
Avatar of ashsysad
ashsysadFlag for United States of America

asked on

Command to have a count of matching string


I need a command-set or script in Perl which will take a String and File-name as inputs and displays the number of times the String is present in that file.  Using 'grep' command with -c option will display the number of matching lines in which the String is present but not the count.  Please let me know.

Avatar of Maciej S
Maciej S
Flag of Poland image

sed 's/your string/&\n/g' your_file | grep -c 'your string'

Open in new window

This will cause that there will be only one 'your string' per line. Then "grep -c" will count these lines.
is the number of matching lines in which the String is present different from the count because the string may occur more than once on a line?

If so, you might use something like

perl -lne 'BEGIN{$_=shift}END{print $.-1}' String File-name

(this assumes that the last String in the file is followed by a newline or some other character)
Avatar of ashsysad


Hi Ozo,  I'm not getting the correct value with your syntax. Could you please check ?
The output should be 10 in the below example.

[root@iss-chi-rad01 ashok]# cat testfile
A disk "snapshot" is a copy of the virtual machine disk file (VMDK) at a certain point in time. It preserves the disk file system and  \n
system memory of your VM by enabling you to revert to the snapshot in case something goes wrong. Snapshot can be real lifesavers when \n
upgrading or patching applications and servers. This article will go over everything you need to know about using snapshot with VMware,  \n
including what they are, how they work and advanced techniques. A virtual machine provides several operations for creating and managing  \n
snapshots and snapshot chains. These operations let you create snapshots, revert to any snapshot in the chain, and remove snapshots. You  \n
can create extensive snapshot trees.
[root@iss-chi-rad01 ashok]# perl -lne 'BEGIN{$_=shift}END{print $.-1}' snapshot testfile
[root@iss-chi-rad01 ashok]#
Avatar of Tintin

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry I don't know how
perl -lne 'BEGIN{$/=shift}END{print $.-1}'
got changed to
perl -lne 'BEGIN{$_=shift}END{print $.-1}'
but that will only count the 9 "snapshot"s not the "Snapshot"
If you want case independent matching, you might try
perl -lne 'BEGIN{$r=qr/\Q@{[shift]}/i}$c+=()=/$r/g;END{print $c}' snapshot testfile
Thanks Tintin. That works perfectly.