Count number of lines under each header in a text file using bash shell script
-
I can do this easily in python or some other high level language. What I am interested in is doing this with bash. Here is the file format: head-xyz item1 item2 item3 head-abc item8 item5 item6 item9 What I would like to do is print the following output: head-xyz: 3 head-abc: 4 header will have a specific pattern similar to the example i gave above. items also have specific patterns like in the example above. I am only interested in the count of items under each header.
-
Answer:
You can use awk: awk '/head/{h=$0}{c[h]++}END{for(i in c)print i, c[i]-1}' input.file
powerrox at Stack Overflow Visit the source
Other answers
Note: Bash version 4 only (uses associative arrays) #!/usr/bin/env bash FILENAME="$1" declare -A CNT while read -r LINE || [[ -n $LINE ]] do if [[ $LINE =~ ^head ]]; then HEADLINE="$LINE"; fi if [ ${CNT[$HEADLINE]+_} ]; then CNT[$HEADLINE]=$(( ${CNT[$HEADLINE]} + 1 )) else CNT[$HEADLINE]=0 fi done < "$FILENAME" for i in "${!CNT[@]}"; do echo "$i: ${CNT[$i]}"; done Output: $ bash countitems.sh input head-abc: 4 head-xyz: 3 Does this answer your question @powerrox ?
Michal Gasek
If you don't consider sed a high-level language, here's another approach: for file in head-*; do echo "$file: \c" sed -n '/^head-/,${ /^head-/d /^item[0-9]/!q p } ' <$file | wc -l done In English, the sed script does Don't print by default Within lines matching /^head-/ to end of file Delete the "head line" After that, quit if you find a non-item line Otherwise, print the line And wc -l to count lines.
Jonathan Ross
Related Q & A:
- how to parse a xml file using jquery and phonegap?Best solution by Stack Overflow
- How to Creating text File using Python?Best solution by Stack Overflow
- Is there a limit on the size of a new file or a text file?Best solution by Stack Overflow
- How to search for a particular string in a text file using java?Best solution by Stack Overflow
- How do I open a .doc file using yahoo mail?Best solution by answers.yahoo.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.