linux - 使用 grep 查找并写入带有条件的特定行

标签 linux shell

我是 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/

相关文章:

当年份是两位数时,python从字符串中断转换日期

Unix:如何读取多行?

调试监控

LInux 恢复脚本返回意外标记

c++ - Ubuntu 上的 Google Earth C++ API 库错误

linux - 无法在 RHEL 6.4 中设置网络

ruby - 通过 Travis CI 在 Matrix 中使用带有 Ruby 和 Shell 的多个操作系统

php - Postgres 和 PHP "Ident authentication failed for user"

PHP shell_exec() 没有执行——没有错误

java - 如何在 Java 中执行 shell 命令?