Padding leading zero

hi All
i am new to linux...

source txt ..

281-BUM-5M BUM-5M 0 0
282-BUM-5M BUM-5M 0 0
83-BUM-5M BUM-5M 0 0

is it possible to use bash script to convert to
(remove the "-" and fill up to 4 digit" ?

0281 BUM-5M BUM-5M 0 0
0282 BUM-5M BUM-5M 0 0
0083 BUM-5M BUM-5M 0 0

thanks a lot.

Hi

awk '{x=substr($0,1,index($0,"-")-1);y=substr($0,index($0,"-")+1);printf "%04d %s\n",x,y;}' file

Guru.

1 Like

This is a pure shell solution - should work in bash as well.

#!/usr/bin/env ksh

while read first rest
do
    printf "%04d %s %s\n" ${first/-/ } "$rest"
done <data-file
exit
2 Likes

Without a loop:

$ cat testfile | sed -r 's/^([0-9]+)-/\1 /' | xargs printf "%04d %s %s %d %d\n" 
0281 BUM-5M BUM-5M 0 0
0282 BUM-5M BUM-5M 0 0
0083 BUM-5M BUM-5M 0 0

Or (for our pedants):

$ sed -r 's/^([0-9]+)-/\1 /' testfile | xargs printf "%04d %s %s %d %d\n" 
1 Like

thanks a lot. i got methods of doing this. thanks so much.

while IFS=- read nr rest; do 
  printf "%04d %s\n" "$nr" "$rest"
done < infile
awk '{sub(/-/,FS);$1=sprintf("%04d",$1)}1' infile