如何从日志文件中剪切部分?

19 logs text-processing

我有一个 8 Gb 的日志文件(Rails 生产日志)。我需要在某些日期(行)之间剪切它。我可以使用哪个命令来执行此操作?

aso*_*ove 12

就像是

sed '1,/last date prior to chunk/d;/first date after chunk/,$d' logfile | tee cut-log | less
Run Code Online (Sandbox Code Playgroud)

tee cut-log允许您在屏幕上查看文件中的内容cut-log

编辑:

为了满足 fred.bear 的严格标准,这里有一个 sed 解决方案(尽管可以说 awk 解决方案更漂亮):

b=BB; e=EE ;echo -e "AA\nAA\nBB\nBB\nCC\nCC\nDD\nDD\nEE\nEE\nFF\nFF" | sed -n ":b;/$b/b p;n;b b;:p;p;n;/$e/b e;b p;:e;p;n;/$e/b e;q"
Run Code Online (Sandbox Code Playgroud)

  • @dogbane:是的,是的。已编辑。我敢肯定,您有时编写的代码并不理想,值得如此严厉的评论吗? (3认同)

dog*_*ane 6

要打印 FOO 和 BAR 之间的所有内容,请尝试:

$ sed -n '/FOO/,/BAR/p' file.txt
Run Code Online (Sandbox Code Playgroud)


Pet*_*r.O 5

这将执行您想要的操作...显示
包括和排除参数日期。

# set Test args
set  2011-02-24  2011-02-26  "junk"

from="$1"
till="$2"
file="$3"

# EITHER ====                              +++++++++  
# Ouptut lines between two parameter dates INCLUDING the parameter dates
  awk -v from=$from -v till=$till '
    ($2 >= from) && ($2 <= till) { print $0 ; next }
    ($2 > till) { exit }' "$file"

# OR ========                              ---------
# Ouptut lines between two parameter dates EXCLUDING the parameter dates
  awk -v from=$from -v till=$till '
    ($2 > from) && ($2 < till) { print $0 ; next }
    ($2 >= till) { exit }' "$file"
Run Code Online (Sandbox Code Playgroud)

它测试字段 2 中的(排序的)日期......这是测试数据的示例

    98  2011-02-05 xxxx
    99  2011-02-05 xxxx
   100  2011-02-06 xxxx
   101  2011-02-06 xxxx
Run Code Online (Sandbox Code Playgroud)

这是测试数据生成器