Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I replace spaces in specific position in record with zeros?

Status
Not open for further replies.

turnersn

Programmer
Apr 11, 2000
6
US
I have a file that I need to look at positions 335 -> 344 and if any of these positions are a space, make them a zero.
 
This is one way it could be done:

In this example I am starting at column 34 and going 10
spaces replacing any spaces with zeroes.

I capture the record in substrings just before the start
position, the start through end position, and the balance
of the record.

echo "This is the one I want to change a b c d the spaces to zeros in!" |
nawk 'BEGIN{FS=""}

{
one = substr($1,1,33)
two = substr($1,34,10)
three = substr($1,44)
$1 = gsub(" ","0",two)
$0 = sprintf("%s%s%s\n", one, two, three)
print
}'

This will output 0a0b0c0d00 in place of the substring
between positions 34 and 43. Note the last two were
spaces, so they got changed to zeroes. So any or all
spaces within the subject substring will be changed, but
non-spaces are passed through.

This works because setting $1 forces awk/nawk/gawk
to recompute $0 and thus make the global substitution
that we want.

simply edit the column positions to your needs, get rid
of the echo being piped in and add your input file and
redirect into some output file and it should work O.K.

Hope this helps you!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top