-1

I have a text file which contains texts as below:

ITEM
preset_date 23/10/15
preset_time 22:00:00:00
title Buletin Awani Headlines
clip TAPE_REPLACEMENT
in_src 0
out_src 1500
mode 2
no_vision_trans 1
no_audio_trans 1
type 1
logo_0 1
user_data 08_P_152784839
logo_data_0 0
channel_id 2
end
ITEM
preset_date 23/10/15
preset_time 22:01:00:00
title Episode Number 7
clip HJNAW01HM01AA
in_src 902250
out_src 915700
mode 1
no_vision_trans 1
no_audio_trans 1
type 1
logo_0 1
user_data 08_P_152784840
logo_data_0 0
aspect_ratio 2
channel_id 2
use_subtitle 1
subtitle HJNAW01HM01
end

I want to count the number of occurrences of the word logo in the file. How do I want to achieve this using Bash file? Appreciate your assistance ..

uzairi
  • 1
  • 2
  • How would you filter lines that contain a word from a file? – KamilCuk Mar 29 '20 at 17:27
  • 2
    Look into `man grep` – Quasímodo Mar 29 '20 at 17:34
  • 1
    Does this answer your question? [command to count occurrences of word in entire file](https://stackoverflow.com/questions/21603555/command-to-count-occurrences-of-word-in-entire-file) – KamilCuk Mar 29 '20 at 17:47
  • @uzairi: You need to define what exactly you consider to be a "word". For instance, if the file contains the string `xlogoylogoz`, does this count as zero, 1 or two occurances of the _logo_? – user1934428 Mar 30 '20 at 06:25
  • If the word occurs multiple times in a line, I will count is a 1. – uzairi Mar 30 '20 at 17:49

2 Answers2

1

grep -c 'logo' < input file name

Digvijay S
  • 2,665
  • 1
  • 9
  • 21
  • 2
    While this would work for the concrete example posted, it would fail if the word _logo_ occurs several times in a line. – user1934428 Mar 30 '20 at 06:22
0

Pure bash solution.

#!/bin/bash

count=0
match="logo" # note: this is a regular expression

while read -a line ; do
    for word in "${line[@]}" ; do
        [[ $word =~ $match ]] && let 'count=count+1'
    done
done

echo $count

Instructions for how to run

Save the script into count_logo.sh. Make the script executable:

chmod +x count_logo.sh

Run the script with input from your text file (say file.txt) using:

./count_logo.sh < file.txt
rtx13
  • 2,580
  • 1
  • 6
  • 22
  • how do i link with the .txt file in directory folder? – uzairi Apr 03 '20 at 02:26
  • Put the script into a file, say `count_logo.sh`. Make the script executable using `chmod +x count_logo.sh`. Finally run the script with input from your text file (say `file.txt`) using `./count_logo.sh < file.txt`. – rtx13 Apr 03 '20 at 04:05
  • the script will save as .bat file? – uzairi Apr 09 '20 at 17:51
  • @uzairi I suggest naming it `count_logo.sh` in my example. Have a look at **Instructions for how to run**. – rtx13 Apr 09 '20 at 19:00
  • is this executable in windows? – uzairi Apr 13 '20 at 02:03
  • If you have and are running `bash` on windows, you may have to run it like this: `bash count_logo.sh < file.txt` – rtx13 Apr 13 '20 at 02:39