【Shell案例】【tail/head/sed、echo $res ·· cat和管道】2、打印文件的最后5行
描述
经常查看日志的时候,会从文件的末尾往前查看,于是请你写一个 bash脚本以输出一个文本文件 nowcoder.txt中的最后5行
示例:
假设 nowcoder.txt 内容如下:
#include<iostream> using namespace std; int main() { int a = 10; int b = 100; cout << "a + b:" << a + b << endl; return 0; }
你的脚本应当输出:
int a = 10; int b = 100; cout << "a + b:" << a + b << endl; return 0; }
方法1:tail-n 5 文件名方式
类似:
head(-n均可省略)
查看中间使用sed:sed -n ‘5,20p’ filename
#!/bin/bash tail -n 5 nowcoder.txt
tail的用法【可以把参数放到后面,也可以通过管道的方式放到前面】
1、tail -f nowcoder.txt : 实时输出(f)文件的最新更新内容;
2、tail -n 5 nowcoder.txt [或者:tail -5 nowcoder.txt] : 输出文件的最后5行;
3、tail -n +5 nowcoder.txt : 输出从第5行开始到文件结尾(+)的内容;
4、tail -n -5 nowcoder.txt : 输出从倒数 第五行开始到文件结尾的内容;
5、tail nowcoder.txt : 不加任何参数,默认输出10行;
6、tail -c 5 nowcoder.txt : 表示输出文件最后5个字节(c);
方法2:配合语句执行符号`语句`和echo打印$执行结果
#!/bin/bash res=`tail -n 5 nowcoder.txt` echo $res
方法3:管道+cat
#!/bin/bash cat nowcoder.txt | tail -n 5
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/16191916.html

浙公网安备 33010602011771号