To take line count from a file

Hi guys,

I am having a file which where i need to take line count based on searching a particular string from a list say list_file.txt which occurs in 2nd column of my main file and to take the line count which doesnot exist in list file say list_file.txt

for eg: my main file looks like this

1|US|xx|yy
2|AUS|yy|zz
11|NZ|aaa|qqq
12|UK|aa|qq
12|AUS|yyy|z11z
.
.
.

i am having a list file say list_file

AUS
NZ

i need the out put of line count of mail file like this output_file

AUS - 2
NZ -1
REST - 2

I have tried something like this

grep NZ main_file|wc -l
grep AUS mail_file|wc -l

but struck for rest of which is not present in list_file.txt

hope this 'll help work for you

 cut -d'|' -f2 file |sort | uniq -c

--Lohit

Here are a couple of other ways to get what you requested:

Echo "Using shell while read loop:"
rest=$(wc -l < main)
while read cc
do      ccc=$(grep '|'"$cc"'|' main|wc -l)
        printf "%s - %d\n" "$cc" $ccc
        rest=$(($rest - $ccc))
done < list_file
printf "REST - %d\n" $rest
printf "\nUsing awk script:\n"
awk -F'|' '
FNR == NR {
        ccc[$2]++
        rest++
        next
}
{       printf("%s - %d\n", $1, ccc[$1])
        rest -= ccc[$1]
}
END {   printf("REST - %d\n", rest)
}' main list_file

This should work with any POSIX-conforming shell (e.g., ksh or bash). If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .
The output from this script with your two sample files as input is:

Using shell while read loop:
AUS - 2
NZ - 1
REST - 2

Using awk script:
AUS - 2
NZ - 1
REST - 2
1 Like
awk -F'|' 'FNR==NR{a[$0];next} {if ($2 in a) a[$2]++; else a["REST"]++} END { for(i in a) print i, a}' list_file main OFS=' - '
1 Like

if you have Ruby

# get list_file to array
list_file  = File.open("list_file").readlines.map(&:chomp)

line_count = Hash.new { |h,k| h[k] = 0 }  # create dictionary to store counts   
f          = File.new("main_file")
f.each  do |line|
  tag = line.split("|")[1]                # get the tag
  if list_file.include? tag               # if inside line_count array
     line_count[ tag ] += 1               # increment
  end  
end
f.close                                   # file close
line_count.each_pair do |x,y|
  puts "#{x} : #{y}"                      # display result
end