To work out the maximum length of a string of same characters (in this example
a's and A's), a solution using the ksh is:
#!/usr/bin/sh
MAX=0
while read LINE
do
LENGTH=`echo $LINE | tr -cs "[a][A]" "[#*]" | awk '
BEGIN { FS = "#" }
max=0
{
for (i =1; i < NF; ++i )
len = length($i)
if ( len > max) max = len}
{print max }'`
if [ $LENGTH -gt $MAX ]; then
MAX=$LENGTH
fi
done
echo $MAX
This will read stdin a line at a time, all characters except a and A are converted
into a single # (tr command). The awk script then separates the fields
using # as the deilimiter, works out the length of each string on a line and prints
the maximum value. If this is bigger than the current maximum ($MAX), $MAX
is set to this value. Once all the lines are processed, the value is echoed to stdout.
To do the same in the csh shell:
#!/usr/bin/csh
set MAX = 0
while ( 1 )
set LINE = "$<"
if ( "$LINE" == "" ) then
break
endif
set LENGTH = `echo $LINE | tr -cs "[a][A]" "[#*]" | awk -f test.awk`
if ( $LENGTH > $MAX ) then
set MAX = $LENGTH
endif
end
echo $MAX
In this example the awk script is in a separate file test.awk