-1

I have a data in file.txt like below

N4*1
NM1*IL*2
PER*IC*XM*

how can i read line by line and get the character * count ?

Pseudocode

#!bash/sh
cd `dirname $0`

filelinecount=echo '$(wc -l file.txt)'

if [ $filelinecount -gt 0 ] ; then

      for (int i=0, i++); do 
         fileline=$i  (STORES LINE IN VARIABLE)
         charactercount= cat '$fileline | wc [*] $fileline'
        (GET CHARACTER [*] COUNT AND STORED IN VARIABLE)
         echo $charactercount 
      done
else
   echo "file.txt don't contain any lines"
fi 

Expected output: 'For' Loop should read line by line from file and store each line in variable "fileline" then count the characters [*] and store in variable "charactercount" then print the variable $charactercount. This loop has to repeat for for all the files in the file. How can i achieve this in 'for' loop ?

1
2
3

This is not a duplicate question as this question clearly asked count of characters using "for" loop. "Count occurrences of a char in a string using Bash" post don't have answer to this post

skv
  • 100
  • 10

2 Answers2

0
tr -d -c '*\n' file.txt | awk '{print length}'

Remove everything except stars and newlines from the file. Then print the line lengths.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0
awk '{print gsub(/\*/,$0)}' file

To achieve the same in a loop:

#! /bin/bash

while read line
do
    grep -o '*' <<<"$line" | grep -c .
done < file

This should print * count per line.

Update as per the comment:

#! /bin/bash


while read line
do

    echo "$line" | awk -F"[*]" '{print NF-1}'
done < file

[ ! -s file ] && echo "no lines in file"

[ ! -s file ] has nothing to do with loop. -s flag checks if file has contents. If it has t returns true. But in your case you want opposite behaviour so we used !. So when file is empty, it returns true and && causes the next command to execute i.e. echo "no lines in file”.

Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39