尝试将 cat、sed 和 grep 串在一起。
sed '3!d' filename | grep Third
未命名或anonymous pipe (|) 和redirection () 是许多shell 的强大功能。它们允许组合一组命令来执行更复杂的功能。
在这个问题的情况下,有两个明确的步骤,
1)对文件的特定行进行操作(例如过滤文件)
2) 在过滤器的输出中搜索特定的字符串
认识到有两个步骤是需要组合两个命令的有力指标。因此,可以通过为每个步骤找到解决方案,然后通过管道和重定向将它们组合成一个命令来解决问题。
如果您了解 Stream Editor (sed),在考虑如何完成过滤文件的第一步时,您可能会想到它。如果不搜索,“linux get a specific line of a file”this OS question 在搜索结果中排名靠前。
$ cat tmp.txt
this is the first line
this is the Second line
This is the Third. line
$ sed '3!d' tmp.txt
This is the Third. line
知道 grep 可以搜索带有感兴趣字符串的行,下一个挑战是弄清楚如何将 sed 的输出作为 grep 的输入。管道 (|) 解决了这个问题。
sed '3!d' filename | grep Third
示例输出:
$ sed '3!d' tmp.txt | grep Third
This is the Third. line
$
shell 脚本中另一个强大的概念是exit status。 grep 命令将在找到匹配项时将退出状态设置为 0,在未找到匹配项时设置为 1。 shell 将退出状态存储在一个名为 $? 的特殊变量中。 (对于bash)。因此,可以使用退出状态来有条件地确定 shell 脚本中的下一步。下面的示例没有实现条件(如 if、else)。下面的示例显示了使用 echo 命令的退出状态值。
$ sed '3!d' tmp.txt | grep Third
This is the Third. line
$ echo $?
0
$ sed '3!d' tmp.txt | grep third
$ echo $?
1
$