1

我有以下 dmesg 示例:

 throttled log output.
57458] bar 3: test 2 on bar 8 is available
[   19.696163] bar 1403: test on bar 1405 is available
[   19.696167] foo: [   19.696168] bar 3: test 5 on bar 1405 is available
[   19.696178] foo: [   19.696179] bar 1403: test 5 on bar 1405 is available
[   20.928730] foo: [   20.928733] bar 1403: test on bar 1408 is available
[   20.928742] foo: [   20.928745] bar 3: test on bar 1408 is available
[   24.878861] foo: [   25.878861] foo: [   25.878863] bar 1403: bar 802 is present

我想将行中的所有时间戳转换为人类格式("%d/%m/%Y %H:%M:%S"

注意:这个系统没有也dmesg -T没有安装 perl。我更喜欢带有 sed 或 awk 的解决方案,但 python 也是一种选择。

我找到了一些解决这个问题的方法,但没有一个能完全满足我的需求。我也不知道如何根据我的需要修改它。

awk -F"]" '{"cat /proc/uptime | cut -d \" \" -f 1" | getline st;a=substr( $1,2, length($1) - 1);print strftime("%d/%m/%Y %H:%M:%S",systime()-st+a)" "$0}'

或者

sed -n 's/\]//;s/\[//;s/\([^.]\)\.\([^ ]*\)\(.*\)/\1\n\3/p' |  while read first; do    read second;    first=`date +"%d/%m/%Y %H:%M:%S" --date="@$(($seconds - $base + $first))"`;   printf "[%s] %s\n" "$first" "$second";  done

这里还有一个 python 脚本。但是输出一些我对它的理解为零的错误。

谢谢!

4

2 回答 2

3

以下代码模拟dmesg -T结果。它是 shell 内的内联 awk,可以存储为独立脚本或 shell 函数:

awk -v UPTIME="$( cut -d' ' -f1 /proc/uptime )" '
BEGIN {
    STARTTIME = systime() - UPTIME
}
match($0, /^\[[^\[\]]*\]/) {
    s = substr($0, 2, RLENGTH - 2) + STARTTIME;
    s = strftime("%a %b %d %H:%M:%S %Y", s);
    sub(/^\[[^\[\]]*\]/, "[" s "]", $0);
    print
}
'

它不能保证提供的精度,dmesg -T但会使结果更接近。

于 2021-05-12T13:37:17.963 回答
1

这有点简单,但它至少应该给你一些可以使用的东西:

awk '
  {
    # tail will be the part of the line that still requires processing
    tail = $0;                               

    # Read uptime from /proc/uptime and use it to calculate the system
    # start time
    "cat /proc/uptime | cut -d \" \" -f 1" | getline st;
    starttime = systime() - st;

    # while we find matches
    while((start = match(tail, /\[[^[]*\]/)) != 0) {
      # pick the timestamp from the match
      s = substr(tail, start + 1, RLENGTH - 2);

      # shorten the tail accordingly
      tail = substr(tail, start + RLENGTH);

      # format the time to our preference
      t = strftime("%d/%m/%Y %H:%M:%S", starttime + s);

      # substitute it into the original line. [] are replaced with || so
      # the match is not re-replaced in the next iteration.
      sub(/\[[^[]*\]/, "|" t "|", $0);
    }

    # When all matches have been replaced, print the line.
    print $0
  }' foo.txt
于 2014-12-16T19:46:57.727 回答