linux 如何在/var/log/dpkg. log中搜索每月安装/升级日志并输出到文本文件

w46czmvw  于 2022-12-11  发布在  Linux
关注(0)|答案(2)|浏览(140)

我想通过在/var/log/dpkg.log中查找,输出一个安装/升级日志仅限于上个月的文件。
我不知道bash,我知道grep命令可以,但我仍然需要一些帮助。

js4nwp54

js4nwp541#

$ grep "install\|upgrade" /var/log/dpkg.log | grep "2021-01" > log.dat

示例输出:

2021-01-11 23:05:50 status installed mime-support:all 3.62
2021-01-11 23:05:50 status installed hicolor-icon-theme:all 0.17-2
2021-01-11 23:05:53 status installed shared-mime-info:amd64 1.10-1
2021-01-12 11:11:57 install python3-configobj:all <none> 5.0.6-3
2021-01-12 11:11:57 status half-installed python3-configobj:all 5.0.6-3
2021-01-12 11:11:57 install python3-psutil:amd64 <none> 5.5.1-1
2021-01-12 11:11:57 status half-installed python3-psutil:amd64 5.5.1-1
yi0zb3m4

yi0zb3m42#

Awk是一个理想的解决方案(GNU awk利用了gensub函数)

awk -v tstamp="$(date -d "-30 days" +%s)" '/install/ || /upgrade/ {dconv=gensub("-"," ","g",$1);tconv=gensub(":"," ","g",$2);dstamp=mktime(dconv" "tconv);if (dstamp >= tstamp ) { print } }' /var/log/dpkg.log

说明:

awk -v tstamp="$(date -d "-30 days" +%s)" ' # Pass the date minus 30 days as variable to awk (tstamp)
    /install/ || /upgrade/ {                                  # Process where lines 
                                                                contain install or 
                                                                upgrade
                             dconv=gensub("-"," ","g",$1);    # Replace "-" for " " in 
                                                                the first space 
                                                                delimited field (date) 
                                                                and read result into 
                                                                dcon
                             tconv=gensub(":"," ","g",$2);    # Replace ":" for " " in 
                                                                the second space 
                                                                delimited field (time) 
                                                                and read the result 
                                                                into tconv
                             dstamp=mktime(dconv" "tconv);    # Create epoch format of 
                                                                date and time
                             if (dstamp >= tstamp ) {         # See whether date/time 
                                                                is within 30 days by 
                                                                comparing dstamp to 
                                                                tstamp
                                 print                        # Print line if 
                                                                condition is met
                             } 
                            }' /var/log/dpkg.log

相关问题