修改 cat 命令以对段落进行编号并仅显示最后一段

修改 cat 命令以对段落进行编号并仅显示最后一段

我有一个文本文件,我需要做三件事:

  1. 修改“cat”命令以突出显示关键字,同时显示文件的完整内容。找到解决方案
  2. 修改“cat”命令以自动对段落进行编号。它们由一个空行分隔。
  3. 修改“cat”命令以仅显示最后一段。

棘手的部分是所有这些都需要由修改猫命令。

我看过很多论坛帖子解释说 cat 不适合这个 - 我完全明白为什么。然而,挑战在于我必须使用猫

答案1

你真的需要使用猫吗?

cat -n  thefile | tail -n1 

“突出显示关键字,同时显示文件的完整内容”是什么意思?

您想突出哪些关键词?

对所有段落进行编号但仅显示最后一个段落的目的是什么? (注意:我编写的命令将执行此操作,cat -n 对段落进行编号,tail -n1 仅显示最后一段。)

答案2

祝你在GCSE计算课程教学中好运;)它没有指定在问题中使用cat,至少在问题单上的一个!

我已经做了

perl -00pe ‘s/^/$. /’ textfile

对于 7ii 和

perl -00pe ‘s/^/$. /’ jamestextfile | tail -n1

对于 7iii

问题7中最重要的是使用管道之类的东西。

答案3

我发现这个问题和评论很有趣,所以我更深入地研究了它。根据给出的评论,我明白问题更多是关于“如何修改输出cat 命令的?“,也许只是通过使用命令开关,如果可能的话。请注意,如果给出示例输入并显示预期输出,问题会更容易理解。

假设TEST_FILE给出以下内容:

This is the first (1) paragraph. This is the second (2) sentence. This is the third (3) sentence.\n The fourth (4) sentence of the first (1) paragraph is the second (2) line of the first (1) paragraph.

This is the second (2) paragraph. This is the second (2) sentence of the second (2) paragraph. This is the third (3) sentence of the second (2) paragraph.


This is the third (3) paragraph. This is the second (2) sentence. This is the third (3) sentence of the second (3) paragraph.



This is the fourth (4) paragraph. This is the second (2) sentence of the fourth (4) paragraph. This is the third (3) sentence.




This is the fifth (5) paragraph. This is the second (2) sentence. This is the third (3) sentence.\n The fourth (4) sentence of the fifth (5) paragraph is the second (2) line of the fifth (5) paragraph.

这些段落不是用一个空行分隔的(按照要求),但了解某些命令的工作原理还是很有好处的。

抑制重复的空输出行

cat -s TEST_FILE 
This is the first (1) paragraph. ...

This is the second (2) paragraph. ...

This is the third (3) paragraph. ...

This is the fourth (4) paragraph. ...

This is the fifth (5) paragraph. ...

另外对所有输出线进行编号

cat -s -n TEST_FILE
     1 This is the first (1) paragraph. ...
     2
     3 This is the second (2) paragraph. ...
     4
     5 This is the third (3) paragraph. ...
     6
     7 This is the fourth (4) paragraph. ...
     8
     9 This is the fifth (5) paragraph. ...

并仅对非空输出行进行编号:

cat -s -n -b TEST_FILE
     1 This is the first (1) paragraph. ...

     2 This is the second (2) paragraph. ...

     3 This is the third (3) paragraph. ...

     4 This is the fourth (4) paragraph. ...

     5 This is the fifth (5) paragraph. ...

根据您的“找到的解决方案”,似乎同意使用管道和第二个命令来修改cat命令的输出。至少对于你的第三个要求来说这是必要的。

因此,您可以使用数字行获得相同的结果nl(但前提是空行确实为空且不包含空格):

cat TEST_FILE | nl
     1  This is the first (1) paragraph. ...

     2  This is the second (2) paragraph. ...


     3  This is the third (3) paragraph. ...



     4  This is the fourth (4) paragraph. ...




     5  This is the fifth (5) paragraph. ...

那么就可以删除空行grep还:

cat -s -n -b TEST_FILE | grep .

如果行中包含空格,则需要先将其删除:

grep -v -e '^[[:space:]]*$' TEST_FILE | nl

在 Bash 中回显换行符您可以使用:

echo -e $(cat -s TEST_FILE | tail -1)
echo -e $(cat -s -n -b TEST_FILE | tail -1)

你也可以仅显示某些行号。但这已经超出了问题的范围。

相关内容