使用grep查找和写入具有条件的特定行

时间:2016-05-20 21:45:23

标签: linux shell

我是shell命令的新手。 我需要做一些高级搜索脚本,我不知道该怎么做。

我需要在我的计算机日志文件中查找包含“str1”并且不包含“str2”的行,按日期排序大于或等于某个给定日期,并将结果写入文件,其中进程运行在后台。

以更正式的方式我想这样做:

new_processwritefrom * log * where log_line contain“Str1”&& log_line not contain“str2” order by Date having Date> =%date%)to read.txt)

谢谢你!

1 个答案:

答案 0 :(得分:1)

你可能会使它变得比它需要的更难。 grep 'str1' "$logfile" | grep -v 'str2'会找到包含str1而非str2的所有行。对于指定日期,您需要touchmod时间设置为您要衡量的日期的文件。然后,使用列表提供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

还有其他方法可以解决这个问题,但这是一种相当标准的方法。如果您还有其他问题,请与我们联系。