grep 基础
本课属于 Coddy Terminal 学习旅程的“基础知识”单元。第 34 课,共 82 课。
grep 是 Global Regular Expression Print 的缩写。它是最强大、最常用的终端命令之一。它会搜索文件,并打印出包含匹配模式的每一行。
我们有 server.log:
info: server started
info: listening on port 8080
error: disk full
warning: high memory usage
info: request received
error: connection timeout
info: server shutdown
基本格式是:
grep "pattern" filename例如,要查找包含单词 error 的每一行:
grep "error" server.log输出:
error: disk full
error: connection timeout只会打印包含 error 的行。其他所有行都会被隐藏。
在多个文件中搜索:
grep "error" *.log # 搜索所有 .log 文件搜索包含空格的短语:
grep "connection timeout" server.log区分大小写:
默认情况下,grep 区分大小写。因此,搜索 error 不会匹配 Error 或 ERROR:
grep "error" server.log # 匹配:error
grep "Error" server.log # 匹配:Error
grep "ERROR" server.log # 匹配:ERROR挑战
入门使用 grep 搜索 server.log,并只打印包含单词 error 的行。
提示:格式为
grep "pattern" filename。记住,grep区分大小写:请使用小写的error。
亲手试试
终端
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Terminal 在线编辑器