gsub in Awk to capture count of replaced characters

Hi ,

I am working on a script to replace special characters in ASCII file with '?'.

We need to get count of replaced characters from file. I am new to Awk and i read,

    \# The gsub function returns the number of substitutions made.

I was trying to replace characters with below code,

       gsub("[^[:alnum:][:punct:][:blank:]]","?",$0)

but i am unable to capture the count of replaced characters.

Can anyone help me with the code which will capture the count of replaced characters with above command.

I am kind of in hurry... Thanx in advance.

print gsub("[^[:alnum:][unct:][:blank:]]","?",$0)

Thanx for your quick reply.

That worked.

Can i catch it in a variable ? That would be easier for me.

Sure:

x=gsub("[^[:alnum:][unct:][:blank:]]","?",$0)

This example write the output to a new file.
After that it prints the number of replaced characters and assigns it to the variable var:

var=$(awk '{
  .
  count+=gsub("[^[:alnum:][unct:][:blank:]]","?",$0)
  print $0 > "newfile"
  .
}
END{print count}
' file)

If this works , how can i print values. I had tried this option already but i couldn't print value. I tried like

count=gsub("[[1][unct:][:blank:]]","?",$0)
then print $count
print $'$count'
etc ,

sorry , if i am asking simple Qs ,but it wasted my whole day..


  1. :alnum: ↩ī¸Ž

count=gsub("[^[:alnum:][unct:][:blank:]]","?",$0); 
print count

In AWK most variables are not preceded with "$".

This can be very helpful to me.

But its not workng in ksh script i put. I removed those 2 '.'s from above code.

Any changes required?


  1. :alnum: ↩ī¸Ž

Should work IMHO, did you get errors? Does the file newfile exist?

1 Like
shopt -s extglob
exec 6<"file"
total=0
while read -r LINE<&6
do
    olen="${#LINE}"
    LINE=${LINE//[^[:ascii:]]/}
    len="${#LINE}"
    total=$((olen-len+total))
done
exec 6<&-
echo "Total substitution: $total"

I am getting output like this , no warning/error. Output file is created , but with origional record only , no replacement.

Plz try to figure out exact error....

---------- Post updated at 12:06 PM ---------- Previous update was at 11:45 AM ----------

Sry , the code works perfect .. It was a characater missed by me.

thanks you very much Franklin ....
:):b: