23. Bash Shell - 文本处理:cat、tac、nl、head、tail

开篇词

结合词处理命令,我们可以简便地从文本输出或文本文档中获取我们想要的文本。
 

准备

我们可以借助 echo 命令来将文本输出至一个文件。

准备内容:

echo "First line" >> file.txt
echo "Second line" >> file.txt
echo "Third line" >> file.txt
echo "Fourth line" >> file.txt
echo "Fifth line" >> file.txt
echo "Sixth line" >> file.txt
echo "Seventh line" >> file.txt
echo "Eighth line" >> file.txt
echo "Ninth line" >> file.txt
echo "Tenth line" >> file.txt
echo "Eleventh line" >> file.txt
echo "Twelfth line" >> file.txt
echo "Thirteenth line" >> file.txt
echo "Fourteenth line" >> file.txt
echo "Fifteenth line" >> file.txt
echo "Sixteenth line" >> file.txt
echo "Seventeenth line" >> file.txt
echo "Eighteenth line" >> file.txt
echo "Nineteenth line" >> file.txt
echo "Twentieth line" >> file.txt
echo "Twenty-first line" >> file.txt
echo "Twenty-second line" >> file.txt
echo "Twenty-third line" >> file.txt
echo "Twenty-fourth line" >> file.txt
echo "Twenty-fifth line" >> file.txt
echo "Twenty-sixth line" >> file.txt
echo "Twenty-seventh line" >> file.txt
echo "Twenty-eighth line" >> file.txt
echo "Twenty-ninth line" >> file.txt
echo "Thirtieth line" >> file.txt

追加多行文本至 file.txt 文件
 

借助 cat 来从头开始向下打印文本文件

我们可以借助 cat 命令来从头开始查看文件的文本内容:

cat file.txt

将 file.txt 文件的内容从头开始打印至屏幕上
 

借助 tac 来从尾开始向上打印文本文件

我们可以借助 tac 命令来从尾开始查看文件的文本内容:

tac file.txt

将 file.txt 文件的内容从尾开始打印至屏幕上
 

借助 nl 来打印内容及其对应行号

我们可以借助 nl 命令来显示每行内容的文本内容及其对应的行号:

nl file.txt    # 打印内容及其行号

打印内容及其行号
 

借助 head 来打印文本文件的前 N 行内容

我们可以借助 head 命令来输出文件内容的开头部分:

head file.txt    # 默认情况下打印前十行

打印前 10 行内容
 

结合 n 参数来打印前 20 行

我们可以追加一个 -n 参数来指定要显示的行数:

head -n 20 file.txt    # 打印前二十行

打印前 20 行内容
 

借助 tail 来打印文本文件的后 N 行内容

我们可以借助 tail 命令来输出文件内容的结尾部分:

tail file.txt    # 默认情况下打印后十行

打印后 10 行内容
 

结合 n 参数来打印后 20 行

我们可以追加一个 -n 参数来指定要显示的行数:

tail -n 20 file.txt    # 打印后二十行

打印后 20 行内容
 

借助 more 来打印文件内容并与其交互

我们可以借助 more 命令来查看一个文本文档内容并与其交互:

more file.txt    # 目前已经很少有人用了,适用于内容比较少的文件

在交互模式中将 file.txt 文件的内容打印至屏幕

more 交互模式中的操作

一些可以用于操作的键有:

操作 用途
/string 在随后的内容中查找 string 关键词。
:f 显示文件名及当前行号。
B 键 内容起始位置。
空格键 下一页。
回车键 下一行。
Q 键 不显示余下的内容并退出交互模式。

借助 less 来打印文本文件内容并与其交互

我们也可以借助 less 命令来查看文本文档内容并与其交互:

less file.txt    # 它是 more 的一个增强版本,适用于大型文件

less 交互模式中的操作

一些可以用于操作的键有:

操作 用途
?string 在之前的内容中查找 string 关键词。
/string 在随后的内容中查找 string 关键词。
空格键 下一页。
下一页键 下一页。
下箭头键 下一行。
上一页键 上一页。
上箭头键 上一行。
Q 键 不显示余下的内容并退出交互模式。

我所撰写的英文版本

23. Bash Shell - Text Processing: cat, tac, nl, head, tail
 

引用

参见

想看手册的其他内容?请访问该手册的所属专栏:《Linux 管理员手册:既简单又深刻

发布了77 篇原创文章 · 获赞 6 · 访问量 1614

猜你喜欢

转载自blog.csdn.net/stevenchen1989/article/details/104067407