Forum Stats

  • 3,815,629 Users
  • 2,259,063 Discussions
  • 7,893,190 Comments

Discussions

Changing a string of blanks to a string of 0s in a specific column range in a data file.

rjsosi
rjsosi Member Posts: 237 Bronze Badge
edited Jul 12, 2021 7:44PM in Generic Linux

Hi,

We're using Redhat Linux 7.9 with bsh.

I want to go through a data file and replace all the fields between columns 10 and 20 that have blanks with 0s.


So if I have an example file of:

"#######################

#######################

#######################

#########      ######

#######################

#######################

#######################

#######################"

I want the script to make it look like :

"#######################

#######################

#######################

#########000000000######

#######################

#######################"

#######################

#######################"


I've tried usign the followig:

awk '{val=substr($0,10,19);gsub(val,"     ","000000000")}1' scr1

But it only returns the original file. What did I miss?

Thanks!

Comments

  • User51642 Yong Huang
    User51642 Yong Huang Member Posts: 160 Bronze Badge
    edited Aug 31, 2021 6:26PM
    awk -vOFS=$'\0' '{bf=substr($0,1,9);val=substr($0,10,19);print bf,gensub(" ","0","g",val)}' scr1
    

    Note: val should be the last argument to *sub functions (i.e. gsub, sub, gensub), not the first. Also, I don't think you can do in-place edit. So I save the preceding substring to bf and print bf followed by the return value of gensub (if you used gsub, the return value would be number of replacements). And I set the output field separator to null with OFS (syntax -vOFS='' or -vOFS=$"\0" works for me too).