Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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

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.

Thanks for the response. I already tried in the following way, but somehow it goes into endless loop.
$ cat 1.txt
abc|pqr|ttt|fff|rrrctr=1
while true
do
var=`cat 1.txt | head -1 | cut -d'|' -f$ctr | wc -c`
if [ $var -eq 1 ]
break
fi
ctr=`expr $ctr + 1`
done
#number of field delimeters
echo $ctr

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:
#!/bin/ksh pipecnt=0 while read line do count=0 linelen=`echo "$line"|wc -c` if [ $linelen -gt 0 ] then # don't do anything if line is zero len until [ $count -ge $linelen ] do count=`expr $count + 1` char=`echo "$line"|cut -b"$count"` if [ "$char" = "|" ] then # check if char is pipe pipecnt=`expr $pipecnt + 1` fi done fi done < 1.txt echo $pipecnt # end scriptI'm using ksh so you could use the ksh arithmetic method:
((pipecnt+=1)) # add 1 to pipecnt

well, if OP wants to do it with the shell, something like this may suffice
while read line do x=${line//[!|]/} echo ${#x} done <file

![]() |
auto date stamping a file...
|
create *.txt
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |