3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Linux】awkコマンドで0埋め(ゼロ埋め)で表示する方法

Posted at

###ログファイルの日付表記が以下のようになっていると、見づらいかと思います。

test.log
2018/8/5 00:03:10 [LEVEL0] 1234567890 123450 KEY000 aaa bbb cccccc:555 dddddd:000
2018/9/15 10:04:11 [LEVEL0] 1234567891 123451 KEY000 aaa bbb cccccc:666 dddddd:111
2018/10/5 21:31:05 [LEVEL0] 1234567892 123452 KEY0000 aaa bbb cccccc:777 dddddd:222
2018/11/21 08:13:40 [LEVEL0] 1234567893 123453 KEY0000 aaa bbb cccccc:888 dddddd:333
2019/1/2 22:03:22 [LEVEL0] 1234567894 123454 KEY0000 aaa bbb cccccc:999 dddddd:444

###こんな時、awkコマンドで日付フォーマットをyyyy/mm/ddに変換して表示させると見やすくなります。

test.log
[test@localhost ~]$ cat test.log | awk -F '[ /]' '{printf("%4d/%02d/%02d %08s %10s %10s %6s %7s %3s %3s %10s %10s\n",$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)}'
2018/08/05 00:03:10   [LEVEL0] 1234567890 123450  KEY000 aaa bbb cccccc:555 dddddd:000
2018/09/15 10:04:11   [LEVEL0] 1234567891 123451  KEY000 aaa bbb cccccc:666 dddddd:111
2018/10/05 21:31:05   [LEVEL0] 1234567892 123452 KEY0000 aaa bbb cccccc:777 dddddd:222
2018/11/21 08:13:40   [LEVEL0] 1234567893 123453 KEY0000 aaa bbb cccccc:888 dddddd:333
2019/01/02 22:03:22   [LEVEL0] 1234567894 123454 KEY0000 aaa bbb cccccc:999 dddddd:444

###解説
セパレータに半角スペースと/を指定します。

awk -F '[ /]'

そしてprintfの指定を%02dにします。

%4d/%02d/%02d

%02sでは上手く行きませんので、ご注意が必要です。

%4s%02s%02s
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?