Jnzz
Jnzz

Reputation: 3

Doing count and splitting in bash

Hi guys need some advice on what other possible way is there to achieve the below result

(Before)

    02-10-2019 name_AA_xxxxx.txt  
    02-10-2019 name_AA_xxxxx.txt  
    02-10-2019 name_BB_xxxxx.txt  
    02-10-2019 name_BB_xxxxx.txt  
    02-10-2019 name_CC_xxxxx.txt  

(After)

    02-10-2019 name_AA_xxxxx.txt  
    02-10-2019 name_AA_xxxxx.txt  
    Count : 2  

    02-10-2019 name_BB_xxxxx.txt  
    02-10-2019 name_BB_xxxxx.txt  
    count : 2  

    02-10-2019 name_CC_xxxxx.txt  
    Count 1  

Assumption

Tried to grep and pipe it into WC it will work but its not efficient and i cant reuse the code, did a bit of search and was thinking of using awk command but not sure how i can execute that.

A quick fix im using now is cat input.file | grep TYPENAME for the name and then use cat input.file | grep TYPENAME | wc -l to check the count

any advice would be appreciated.

PS: as i do not wish to leak any sensitive information therefore am trying to provide as much information as i can.

Upvotes: 0

Views: 68

Answers (2)

Šerg
Šerg

Reputation: 803

sort input.file | uniq -c | awk '/name.*/{for (i = 1; i <= $1; ++i) print $3; print "Count : "$1}'

Or if you need especially print particularly for count 1:

sort input.file | uniq -c | awk '/name.*/{for (i = 1; i <= $1; ++i) print $3; if ($1>1) printf "Count : "; else printf "Count "; print $1; }'

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133538

Could you please try following.

awk 'prev!=$2 && count{print "Count : " count;count=""} {count++;prev=$2} END{if(count){print "Count : " count}}' Input_file

With Jnzz' updated input file:

awk -F ' +|_' 'prev!=$3 && count{print "Count : " count;count=""; print ""} {count++;prev=$3; print} END{if(count){print "Count : " count}}' Input_file

Output:

    02-10-2019 name_AA_xxxxx.txt  
    02-10-2019 name_AA_xxxxx.txt  
Count : 2

    02-10-2019 name_BB_xxxxx.txt  
    02-10-2019 name_BB_xxxxx.txt  
Count : 2

    02-10-2019 name_CC_xxxxx.txt  
Count : 1

Upvotes: 1

Related Questions