padding zeros to binary numbers using shell scripting

bash, binary, printf, scripting, shell

Solution

You can use `tr` to replace the spaces you get with zeroes:

printf "%032s\n" $(<binary.txt) | tr ' ' '0'

Problem

How to pad zero to binary numbers using shell script. binary.txt ``` 1010011100010001010111001101111 0 10110000000101000000000000001 10100000011 1000000100 1111111111111111 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 ``` when i do the following ``` printf "%032s\n" $(<binary.txt) ``` I get a white space. ``` 1010011100010001010111001101111 0 10110000000101000000000000001 10100000011 1000000100 1111111111111111 11111111111111110000000000000000 11111111111111110000000000000000 11111111111111110000000000000000 ``` But I need zero's appended. Any input is appreciated. thanks, Updated: binary.txt is my input file and has the following contents. ``` 1010011100010001010111001101111 0 10110000000101000000000000001 10100000011 1000000100 1111111111111111 11111111111111110000000000000000 11111111111111110000000000000000 ``` while running the following command in the command line it works fine. ``` printf "%032s\n" $(<binary.txt) | tr ' ' '0' >> t1.mif ``` But when i try to do the same using a script below , it gives me wrong values. Any suggestions. ``` #!/bin/bash FILE=binary.txt while read line;do printf "%032s\n" $line | tr ' ' '0' >> t1.mif done < $FILE ``` thanks

Original source