Jon
Jon

Reputation: 601

How to zero-fill first column of data

I have data like this in tab separated columns:

1   name1   attribute1
1   name1   attribute2
1   name1   attribute3
31  name2   attribute1
31  name2   attribute2
31  name2   attribute3
444 name3   attribute1
444 name3   attribute2
444 name3   attribute3

And I want to have it like this:

001 name1   attribute1
001 name1   attribute2
001 name1   attribute3
031 name2   attribute1
031 name2   attribute2
031 name2   attribute3
444 name3   attribute1
444 name3   attribute2
444 name3   attribute3

Can I do this in unix or perl for instance?

Upvotes: 0

Views: 189

Answers (3)

rsa
rsa

Reputation: 595

The Awk and Perl answers are both great. I would also add that in Perl, if you don't know ahead of time how many digits you are going to have in the first column, you can replace the "3" in "%03d" part with a scalar value that contains the length of your longest number in the first column.

Upvotes: 1

Steve
Steve

Reputation: 54592

Here's one way using GNU awk:

awk -v OFS="\t" '{ $1 = sprintf ("%03d", $1) }1' file.txt

Upvotes: 0

ikegami
ikegami

Reputation: 386706

perl -i~ -pe's/^(\d+)/sprintf "%03d", $1/e' file

Actually, the above checks more than it needs to. Here's a more general solution:

perl -i~ -pe's/^([^\t]*)/sprintf "%03s", $1/e' file

Upvotes: 5

Related Questions