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
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
# 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