unix script to count delimiter pipe

June 24, 2009 at 13:43:57
Specs: Windows XP
I want get help to write a unix script to count "|" pipe in the flat file.

The first row is header and the record count starts from 2nd row. I want to count the "|" in 2nd row only.

Thanks for your help

See More: unix script to count delimiter pipe

Report •

June 24, 2009 at 17:54:15
awk -F"|" 'NR==2{print NF-1}'  file

next time, try to do it on your own first before posting. that will indicate you put in effort, even if its for homework.

GNU win32 packages | Gawk

Report •

June 25, 2009 at 11:10:31
Thanks for the response. I already tried in the following way, but somehow it goes into endless loop.

$ cat 1.txt

while true
var=`cat 1.txt | head -1 | cut -d'|' -f$ctr | wc -c`
if [ $var -eq 1 ]
ctr=`expr $ctr + 1`
#number of field delimeters
echo $ctr

Report •

June 25, 2009 at 16:28:06
that's a messy way to do what you want. learn how to use awk, as i have it to you.

GNU win32 packages | Gawk

Report •

Related Solutions

June 25, 2009 at 16:32:06
If you played with this on the command line, you'd see that variable var never equals 1 so the while loop cycles forever:

cat 1.txt | head -1 | cut -d'|' -f 4 | wc -c

I do not understand your logic and what you are trying to do.

If you aren't going to use ghostdog's excellent awk one-liner, then consider cycling thru the file a line at a time and counting the pipe symbols:


while read line
   linelen=`echo "$line"|wc -c`
   if [ $linelen -gt 0 ]
   then # don't do anything if line is zero len
      until [ $count -ge $linelen ]
         count=`expr $count + 1`
         char=`echo "$line"|cut -b"$count"`
         if [ "$char" = "|" ]
         then # check if char is pipe
            pipecnt=`expr $pipecnt + 1`
done < 1.txt
echo $pipecnt
# end script

I'm using ksh so you could use the ksh arithmetic method:
((pipecnt+=1)) # add 1 to pipecnt

Report •

June 25, 2009 at 17:50:57
well, if OP wants to do it with the shell, something like this may suffice
while read line
  echo ${#x}
done <file

GNU win32 packages | Gawk

Report •

Ask Question