Search code examples
stringawknumericzero-padding

Prepend leading zeros to each line of a file


I have a file that looks like this:

1:line1
14:line2
135:line3
15:line4

I need to prepend leading zeros to each line to make it look like this:

00001:line1
00014:line2
00135:line3
00015:line4

Is there an easy way to do this in Linux?

I have tried using

awk '{printf "%05d:%s\n", FNR, $0}' file

but this outputted:

00001:1:line1
00002:14:line2
00003:135:line3
00004:15:line4

I should note I did not write this command, I got it from Google and don't really understand how it works


Solution

  • There are many ways, one way is to use awk

    awk -F":" '{OFS=FS; $1 = sprintf("%05d", $1); print}' "${filename}"
    

    To break it down:

    • -F":" set the field seperator to ":", awk will split the lines into columns for each :.
    • OFS=FS set the output field separator to the field separator, this essentially puts ":" back into each line when we output it.
    • $1 = sprintf("%05d", $1) set the first column, $1, to be itself padded with 0's and of length 5.
    • print print the line.