Gheek.net

October 20, 2010

Count (Series of) Character Occurrences in a file

Filed under: linux, shell scripts — lancevermilion @ 1:38 pm

There are times especially in bash/shell scripting when a “bash -n” doesn’t get the job done just right.

To help make sure you have matching characters like below you can use the following. The caveat is that if you have >> in your code it will count those under >> (1 occurrence) and > (2 occurrences).

for i in ' ' '>>' '<<' '(' ')' ']' '[' '{' '}' "'" "\""; do echo "$i occurs: `tr -dc "$i" < /var/local/yum/Build/KS_Build.sh | wc -c` times"; done

<> occurs: 2 times
occurs: 2 times
( occurs: 1 times
) occurs: 1 times
] occurs: 0 times
[ occurs: 0 times
{ occurs: 5 times
} occurs: 5 times
' occurs: 0 times
" occurs: 8 times

#!/bin/bash
#Author: Lance Vermilion
#Description: Script to Build KickStart configs for Different Server Types
#Date: 10/20/10

KSTYPE="$1"
KSCFG_LOCATION="/var/local/yum/Build/5.4/disc1/${KSTYPE}"
SCRIPTLET_DIR="/var/local/yum/Build/5.4/disc1/${KSTYPE}/SCRIPTLET"

INCLUDE()
{
SCRIPTLET="$1"
cat ${SCRIPTLET} >> ${KSCFG_LOCATION}
}

# These must be listed in the order you want them to be run
INCLUDE "SOME SCRIPLET TO INCLUDE"
INCLUDE "SOME OTHER SCRIPLET TO INCLUDE"

Advertisements

Blog at WordPress.com.