面试题答案
一键面试#!/bin/bash
while read line; do
date=$(echo $line | cut -d' ' -f1)
echo -e "\f$date"
echo $line
while read subline; do
subdate=$(echo $subline | cut -d' ' -f1)
if [ "$subdate" == "$date" ]; then
echo $subline
else
break
fi
done
done < log.txt | pr -T -l 50 -h "$(date +%Y-%m-%d)"
解释:
while read line
逐行读取日志文件log.txt
。- 使用
cut -d' ' -f1
提取每行开头的日期。 echo -e "\f$date"
输出分页符\f
并打印当前日期作为页头。- 内部
while
循环继续读取后续行,直到日期改变,这样就把同一天的日志都放在了一起。 - 最后通过
pr
命令对输出进行分页处理,-T
表示不显示页眉页脚,-l 50
设置每页50行,-h "$(date +%Y-%m-%d)"
设置页眉为当前日期。