用 grep -rn 搜索文件内容

用 grep 的递归搜索找出某段文字具体在哪个文件里,并显示文件名和行号。

macOS搜索文件终端低风险
运行 grep -rn "发票金额" ~/Documents,即可在“文稿”里的所有文件中搜索,并打印每处匹配的文件名和行号。

01命令

命令
$ grep -rn "invoice total" ~/Documents

02作用说明

grep -r 会遍历整个文件夹树并逐个查看文件内容,-n 会在每条结果前加上行号,方便直接定位。加 -i 可以忽略大小写(如 grep -rni "发票" ...),用 --include 还能限定文件类型,例如 --include="*.txt"。聚焦搜索也能搜内容,但 grep 是直接读取磁盘上的原始字节,对配置文件、代码和刚创建还没被索引的文本更可靠。

03风险

风险低风险
!注意: grep 只匹配纯文本——对 Pages、PDF、Word 等文档,最多提示“Binary file matches”,需要先转换或解压才能搜到内容。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • GREP(1) - macOS manual page
    Apple (Xcode man pages mirror) · vendor-doc · 2026-09-17
    依据: The manual page documents --recursive for searching directories recursively and -n for printing line numbers with output lines.
  • grep - Search files for matching lines
    SS64 · technical · 2026-09-17
    依据: Documents the -r option ('search recursively through subdirectories') and -n ('each output line is preceded by its relative line number').

最后验证: 2026-09-19 · 分类: 文件与文件夹

06相关方案