我是 shell 命令的新手。 我需要做一些高级搜索脚本,但我不知道该怎么做。
我需要在计算机日志文件中查找包含“str1”且不包含“str2”的行,按大于或等于某个给定日期的日期排序,并将结果写入文件,该进程在后台运行。
我想以更正式的方式做到这一点:
new_process
(write
(from
*log* where
log_line contain
"Str1"&& log_line not contains
"str2"order by
Date
having Date
>= %date%) to
read.txt)
谢谢!
最佳答案
你可能会让事情变得比需要的更加困难。 grep 'str1' "$logfile" | grep -v 'str2'
将找到包含 str1
的所有行而不是str2
。对于给定日期,您需要 touch
具有 mod
的文件时间设置为您想要衡量的日期。然后,您可以使用您的列表来提供 while read -r fname; do
循环并测试[ "$fname" -nt "testfilename" ]
并将满足该条件的文件写入新文件。
您的最终脚本流程将类似于:
newname="${1:-newfile.txt}"
touch -d "date string" testfilename
grep "$str1" "$logfile" | grep -v "str2" | while read -r fname; do
[ "$fname" -nt "testfilename" ] && printf "%s\n" "$fname" > "$newname"
done
rm testfilename ## clean up
还有其他方法可以解决这个问题,但这是一个相当标准的方法。如果您还有其他问题,请告诉我。
关于linux - 使用 grep 查找并写入带有条件的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37356320/