Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

count pipes ("|") in a file 2

Status
Not open for further replies.

mwesticle

Programmer
Nov 19, 2003
51
US
I need a simple nawk, awk, or sed program (or anything else, really) that will count the number of pipe characters in a file. So, if my file looks like this:

222222222222222|2222|2222|222222|||
|222222|222|222222222222||222|
|||22222222|222222222|2|||222222222222|

I need the program to return me: 21

Simple enough, I know... Anyone have any ideas? Thanks in advance!
 
sed -e 's/[^|]//g' file.txt | wc -c

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
ooops - that's a bit better, but still not elegant:

Code:
echo "$(( $(sed -e 's/[^|]//g' -e 's/$//g' file.txt | wc -m) - $(sed -e 's/[^|]//g' -e 's/$//g' file.txt | wc -l) ))"

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
or with awk:

Code:
nawk '{cnt+=gsub("[|]","");} END {print cnt}' file.txt

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Jeez... So much to choose from... Thanks everyone!!!
 
Code:
awk 'BEGIN{RS="|"}END{print NR-1}' file

If the last line of the file lacks a newline character and it ends with a "|", the count will be off by 1.

If you have nawk, use it instead of awk because on some systems awk is very old and lacks many useful features. For an introduction to Awk, see faq271-5564.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top