Grep char count & pipe to sed command

Hi
I am having a 'grep' headache
Here is the contents of my file:

(PBZ,CP,(((ME,PBZ,BtM),ON),((ME,((PBZ,DG),(CW9,PG11))),CW9,TS2,RT1)))

I would like to count out how many times 'PBZ' occurs and then place that number in the line above

3
(PBZ,CP,(((ME,PBZ,BtM),ON),((ME,((PBZ,DG),(CW9,PG11))),CW9,TS2,RT1)))

This is how i am doing so far on my code

grep 'PBZ' FileIn | wc -c | while read i;
do sed '1i\ 
$i' FileIn > Fileout
done

This is what i get for my Fileout
$i(PBZ,CP,(((ME,PBZ,BtM),ON),((ME,((PBZ,DG),(CW9,PG11))),CW9,TS2,RT1)))

I know that there are three main problems here

1) grep 'PBZ' FileIn | wc -c = 70 .... it is counting every character instead of just counting all the 'PBZ'
2) When i do my while read i command, it does not carry the count over to my sed command thus my $i was not changed in my code
3) The $i is being placed before, but on the same line as my string, i would like it to be on a separate line above my string.

If anyone has any suggestions or tips on how i could correct this it would be very much appriciated.:o

grep -c 'PBZ' FileIn | while read i;
do sed '1i\ 
$i' FileIn > Fileout
done

Nope, thats not it :frowning:

grep -c 'PBZ' FileIn gives me a count of 1, and unfortunatly its still not reading through to the sed command.

welcome to my hell!

I rather go to heaven :)...try this:

awk '/PBZ/{s=$0;$0=(gsub("PBZ","") RS $0)}1' file

Now be aware, my understanding of awk is limited, so im sorry if i offend with my bad code

I tested

awk '/PBZ/{s=$0;$0=(gsub("PBZ","") RS $0)}1' FileIn 

however it gave me this
3
(,CP,(((ME,,BtM),ON),((ME,((,DG),(CW9,PG11))),CW9,TS2,RT1)))

it effectivly deleted my PBZ from my files. I tried to reslove this by deleting gsub("PBZ","") but then of course it didnt work atall

how would i go about fixing this without just saying substitute PBZ with PBZ??

awk '/PBZ/{s=$0;$0=(gsub("PBZ","PBZ") RS $0)}1' FileIn 

My fault, I forgot the variable s in the substitution, try this:

awk '/PBZ/{s=$0;$0=(gsub("PBZ","",s) RS $0)}1' file

How about ...

grep -o 'PBZ' in.file | wc -l | while read i
do
  sed "1i\
  $i" in.file >> out.file
done

That awk command works perfectly, thanks (",)

The sed command, is almost there, thanks for the grep -o tip :stuck_out_tongue: I changed it up so it now recognises the variable

 
grep -o 'PBZ' FileIn | wc -l | while read i;
do sed '1i\
'"$i"''  FileIn > File.out
done

this gives: 3(PBZ,CP,(((ME,PBZ,BtM),ON),((ME,((PBZ,DG),(CW9,PG11))),CW9,TS2,RT1)))

but stil having the problem where the '3' wont go on the line above by itself :frowning:

grep 'PBZ' /tmp/FileIn |while read LINE ;do print $(echo $LINE |sed  s/PBZ/PBZ^/g   |tr '^' "\n" |wc -l ) - 1 |bc ;echo $LINE ;done