>显示前三行

head -n 3 filename

> 显示倒数三行

tail -n 3 filename

>显示最后一行的几种方法

1. tail -n 1 filename
2. tail -1 filename
3. sed -n '$p' filename
4. awk 'END {print}' filename

> 指定行

sed ‘/pattern/!p’ infile //匹配pattern的行不输出 
sed -n ‘10,20p’ infile //10到20行
sed -n ‘2,$p’ file //2到最后一行

1、head

head 命令可用于查看文件的开头部分的内容,有一个常用的参数 -n 用于显示行数,默认为 10,即显示 10 行的内容。

命令格式:

head [参数] [文件]  

参数:

  • -q 隐藏文件名
  • -v 显示文件名
  • -c<数目> 显示的字节数。
  • -n<行数> 显示的行数。
#要显示 runoob_notes.log 文件的开头 10 行,请输入以下命令:
head runoob_notes.log

#显示 notes.log 文件的开头 5 行,请输入以下命令:
head -n 5 runoob_notes.log

#显示文件前 20 个字节:
head -c 20 runoob_notes.log

2、tail

#要显示 notes.log 文件的最后 10 行,请输入以下命令:
tail notes.log         # 默认显示最后 10 行

#要跟踪名为 notes.log 的文件的增长情况,请输入以下命令:
tail -f notes.log

#此命令显示 notes.log 文件的最后 10 行。当将某些行添加至 notes.log 文件时,tail 命令会继续显示#这些行。 显示一直继续,直到您按下(Ctrl-C)组合键停止显示。
#显示文件 notes.log 的内容,从第 20 行至文件末尾:
tail -n +20 notes.log

#显示文件 notes.log 的最后 10 个字符:
tail -c 10 notes.log

3、sed

#显示最后一行
sed -n '$p' log.txt

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐