Reputation: 518
I have a list of lines like
50000
12345
2345
12341
3456
I want to append a character 0 at the beginning to the lines having only 4 characters so that the result is something like this
50000
12345
02345
12341
03456
How can I do it efficiently. Don't ask me to use a loop. Is there anything using awk.
Upvotes: 0
Views: 92
Reputation: 753725
It is tempting to suggest:
awk '{printf "%05d\n", $1}' file
This prints the first field of the file as a zero-padded 5-digit number. It will handle inputs such as 1, 23, 456 as well as 2345 (producing 00001, 00023, 00456, 02345). However, it does assume that the inputs are all numbers; it will not work so well if they're alphanumeric strings, for example.
Upvotes: 4
Reputation: 77105
You can use the length()
function of awk
.
$ awk 'length($0)==4{$0=0 $0}1' file
50000
12345
02345
12341
03456
We use the pattern length($0)==4
to check if the line is 4 characters long. If it is we append 0
in front of it. 1
allows us to print the lines that don't match our criteria as is.
Upvotes: 3