有更干净的方法吗?首选大型 input.txt 文件的单次传递。到目前为止的解决方案:
grep -e "\[.*fred" input.txt |sed 's/.*\[\([^]]*\)\].*/\1/g' |grep -vf /dev/stdin input.txt
解释:
grep -e "\[.*fred" input.txt |
查找标有“fred”且在行中“fred”之前有左方括号的行。发给
sed 's/.*\[\([^]]*\)\].*/\1/g' |
查找方括号之间的 ID,标识文件中的所有“fred”条目。每个“fred”标签的相同 ID 条目的数量不固定,该示例显示每个“fred”有 2 行,但它可以是任意数量。发给
grep -vf /dev/stdin input.txt
从文件中删除具有这些 ID 的所有行。 (根据需要将 /dev/stdin 替换为“-”,即管道输入)
输入.txt:
Jan 2 10:45:01 TecMint CRON[3383]: pam_unix(cron:session): session opened for user root by (fred)
Jan 2 10:45:01 TecMint CRON[3383]: pam_unix(cron:session): session closed for user root
Jan 2 10:51:34 TecMint sudo: tecmint : TTY=unknown ; PWD=/home/tecmint ; USER=root ; COMMAND=/usr/lib/linuxmint/mintUpdate/checkAPT.py
Jan 2 10:51:34 TecMint sudo: pam_unix(sudo:session): session opened for user root by (fred)
Jan 2 10:51:39 TecMint sudo: pam_unix(sudo:session): session closed for user root
Jan 2 10:55:01 TecMint CRON[4099]: pam_unix(cron:session): session opened for user root by (fred)
Jan 2 10:55:01 TecMint CRON[4099]: pam_unix(cron:session): session closed for user root
Jan 2 11:05:01 TecMint CRON[4138]: pam_unix(cron:session): session opened for user root by (fred)
Jan 2 11:05:01 TecMint CRON[4138]: pam_unix(cron:session): session closed for user root
Jan 2 11:09:01 TecMint CRON[4146]: pam_unix(cron:session): session opened for user root by (fred)
Jan 2 11:05:01 TecMint CRON[4199]: pam_unix(cron:session): session opened for user root by (bill)
Jan 2 11:05:01 TecMint CRON[4199]: pam_unix(cron:session): session closed for user root
期望的输出:
Jan 2 10:51:34 TecMint sudo: tecmint : TTY=unknown ; PWD=/home/tecmint ; USER=root ; COMMAND=/usr/lib/linuxmint/mintUpdate/checkAPT.py
Jan 2 10:51:34 TecMint sudo: pam_unix(sudo:session): session opened for user root by (fred)
Jan 2 10:51:39 TecMint sudo: pam_unix(sudo:session): session closed for user root
Jan 2 11:05:01 TecMint CRON[4199]: pam_unix(cron:session): session opened for user root by (bill)
Jan 2 11:05:01 TecMint CRON[4199]: pam_unix(cron:session): session closed for user root
答案1
我认为如果你想删除文件中的任何位置如果行与从文件中任何位置提取的 ID 相匹配,则无法一次性完成此操作。
但是,如果您只需要删除最近匹配的行,那么您可以执行以下操作:
$ perl -lne '$pid = $1 if /(\[.*?\]).*fred/; print unless index($_,$pid) > -1' input.txt
Jan 2 10:51:34 TecMint sudo: tecmint : TTY=unknown ; PWD=/home/tecmint ; USER=root ; COMMAND=/usr/lib/linuxmint/mintUpdate/checkAPT.py
Jan 2 10:51:34 TecMint sudo: pam_unix(sudo:session): session opened for user root by (fred)
Jan 2 10:51:39 TecMint sudo: pam_unix(sudo:session): session closed for user root
Jan 2 11:05:01 TecMint CRON[4199]: pam_unix(cron:session): session opened for user root by (bill)
Jan 2 11:05:01 TecMint CRON[4199]: pam_unix(cron:session): session closed for user root