0

タブ区切りの列に次のようなデータがあります。

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

そして、私はそれを次のようにしたい:

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

たとえば、unix や perl でこれを行うことはできますか?

4

3 に答える 3

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

実際、上記は必要以上にチェックしています。より一般的な解決策は次のとおりです。

perl -i~ -pe's/^([^\t]*)/sprintf "%03s", $1/e' file
于 2012-10-04T16:44:21.853 に答える
1

Awk と Perl の回答はどちらも素晴らしいものです。Perl にも追加します。最初の列に何桁あるのか事前にわからない場合は、「%03d」部分の「3」を、次を含むスカラー値に置き換えることができます。最初の列の最も長い数字の長さ。

于 2012-10-05T02:07:27.177 に答える
0

を使用する 1 つの方法を次に示しGNU awkます。

awk -v OFS="\t" '{ $1 = sprintf ("%03d", $1) }1' file.txt
于 2012-10-04T23:08:15.257 に答える