如何从dbus-monitor输出中提取系统通知的标题、消息与时间?
提取D-Bus通知的标题、内容和时间的Bash脚本
以下是一个直接可用的Bash脚本,通过dbus-monitor监听系统通知,并精准提取标题、多段消息内容和接收时间,输出符合你要求的格式:
#!/bin/bash dbus-monitor "interface='org.freedesktop.Notifications'" | awk ' BEGIN { title = "" message = "" time_str = "" collecting_msg = 0 } # 捕获第一个字符串作为通知标题 /string "/ && title == "" { title = substr($0, index($0, "\"") + 1) title = substr(title, 1, length(title) - 1) next } # 捕获后续的字符串作为消息内容(支持多段) /string "/ { msg_segment = substr($0, index($0, "\"") + 1) msg_segment = substr(msg_segment, 1, length(msg_segment) - 1) if (collecting_msg == 0) { message = msg_segment collecting_msg = 1 } else { message = message ", " msg_segment } next } # 提取时间戳并转换为可读格式 /uint32 [0-9]+/ && time_str == "" { timestamp = $2 time_str = strftime("%Y-%m-%d %H:%M:%S", timestamp) next } # 当检测到通知方法调用结束时,输出结果并重置变量 /method call time=/ { if (title != "" && message != "" && time_str != "") { printf "Title: \"%s\" Message: %s Time: %s\n", title, message, time_str title = "" message = "" time_str = "" collecting_msg = 0 } } '
关键说明
- 标题捕获:将通知输出中的第一个
string字段识别为标题,适配所有应用的通知。 - 多段消息处理:自动拼接后续的
string字段作为消息内容,用逗号分隔。 - 时间转换:提取通知自带的
uint32时间戳,通过strftime转换为YYYY-MM-DD HH:MM:SS格式的可读时间。 - 状态重置:每处理完一条完整通知后,自动重置变量,准备捕获下一条通知。
使用方法
- 将脚本保存为
notify-extractor.sh - 赋予执行权限:
chmod +x notify-extractor.sh - 运行脚本:
./notify-extractor.sh,之后系统触发的通知会自动按指定格式输出。
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

