Behrooz Karjoo
Behrooz Karjoo

Reputation: 4292

How to count how many time a word occurs in an xml file

I was given the task of doing quality check on a machine translation xml file. The translations are from English to a foreign language. I have about 2000 translation blocks in the file and I have to check 200 of them by adding my remarks in the block enclosed in a < comment > tag with a quality attribute. Is there a linux command or some text editor out there which can count the number of comment tags I add or just the number of time the word '/comment' occurs so I don't have to keep track manually?

Upvotes: 3

Views: 4463

Answers (5)

Mads Hansen
Mads Hansen

Reputation: 66783

This XSLT stylesheet can be run on any platform and will tell you how many comment elements there are in the XML document:

<?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet
   version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="UTF-8" omit-xml-declaration="yes"/>
  <xsl:template match="/">
    <xsl:value-of select="count(//comment)"/>
  </xsl:template>
</xsl:stylesheet>

If you add a XSLT processing instruction at the top of the XML file that points to this XSLT( e.g. <?xml-stylesheet href="countComments.xsl" type="text/xsl"?> ), then you could just load the XML file in a browser and see the number displayed.

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342649

your tag says linux, so i assume you have *nix tools like awk

awk '{for(i=1;i<=NF;i++){if($i=="/comment"){++c} } }END{print "total: "c}' xmlfile

Upvotes: 0

Matt Luongo
Matt Luongo

Reputation: 14849

As long as the comments appear on their own line, you could try

cat file | grep -c comment

The -c stands for 'count'.

Upvotes: 0

Rob H
Rob H

Reputation: 15000

grep '/comment' yourfile.xml -o | wc -l

Upvotes: 8

John Feminella
John Feminella

Reputation: 311605

If you know that the </comment> doesn't occur more than once per line, just use grep -c "</comment>". Example:

[~/.logs]> grep -c ldap johnf.2010-02-12.log
103

This searches for the string ldap in the file johnf.2010-02-12.log. The string appears on 103 distinct lines.

Upvotes: 0

Related Questions