Skip to content
← 返回macOS列表
命令与观察

macOS:文本处理与检索 ​

读取、查看与检索 ​

head(macOS) · 输出文件的开头部分 ​

另请参阅:tail。 更多信息:https://keith.github.io/xcode-man-pages/head.1.html。

  • 输出文件的前几行:
bash
head -n {{行数}} {{文件名}}
  • 输出文件的前几个字节:
bash
head -c {{字节数}} {{文件名}}

look(macOS) · 查找已排序的文件行(注意,必须是已排序的文件) ​

查找已排序的文件行(注意,必须是已排序的文件)。 另请参阅:grep, sort。 更多信息:https://keith.github.io/xcode-man-pages/look.1.html。

  • 它开始寻找一个给定的前缀:
bash
look {{前缀}} {{文件}}
  • 查找行,忽略大小写:
bash
look {{[-f|--ignore-case]}} {{前缀}} {{文件}}

创建、修改与转换 ​

sed(macOS) · 以可用脚本的来批量编辑文本 ​

另请参阅:awk, ed。 更多信息:https://keith.github.io/xcode-man-pages/sed.1.html。

  • 替换每一行中首次匹配的字符串,并打印结果:
bash
sed 's/{{查找内容}}/{{替换内容}}/' {{文件名}}
  • 替换文件中所有符合regex式的部分:
bash
sed -E 's/{{正则表达式}}/{{替换内容}}/g' {{文件名}}
  • 替换文件中所有出现的字符串,覆盖文件(直接覆盖文件):
bash
sed -i '' 's/{{查找内容}}/{{替换内容}}/g' {{文件名}}
  • 仅替换与行模式(一种搜索条件)匹配的行内容:
bash
sed '/{{行模式}}/s/{{查找内容}}/{{替换内容}}/' {{文件名}}
  • 从指定行打印到其后第一个空行(包含边界行):
bash
sed -n '{{行号}},/^$/p' {{文件名}}
  • 将多个查找替换表达式应用于文件:
bash
sed -e 's/{{查找内容}}/{{替换内容}}/' -e 's/{{查找内容}}/{{替换内容}}/' {{文件名}}
  • 将分隔符 / 替换为查找或替换模式中没有用到的的任何其他字符,例如 #(用于查找或替换内容中使用了 / 的情况):
bash
sed 's#{{查找内容}}#{{替换内容}}#' {{文件名}}

专用工具与其他操作 ​

base64(macOS) · 使用 Base64 来进行编码和解码 ​

更多信息:https://keith.github.io/xcode-man-pages/bintrans.1。

  • 编码目标文件:
bash
base64 {{[-i|--input]}} {{目标文件}}
  • 解码目标文件:
bash
base64 {{[-d|--decode]}} {{[-i|--input]}} {{base64 编码文件}}
  • 通过标准输入管道进行编码:
bash
echo -n "{{目标字符串}}" | base64
  • 解码标准输入管道内容:
bash
echo -n {{base64 字符串}} | base64 {{[-d|--decode]}}

textutil(macOS) · 用于操作各种格式的文本文件 ​

更多信息:https://keith.github.io/xcode-man-pages/textutil.1.html。

  • 显示有关 foo.rtf 的信息:
bash
textutil -info {{foo.rtf}}
  • 将 foo.rtf 转换为 foo.html:
bash
textutil -convert html {{foo.rtf}}
  • 将带格式的 rtf 文本转换为普通 txt 文本:
bash
textutil {{foo.rtf}} -convert txt
  • 将 foo.txt 转换为 foo.rtf, 字体使用 Times 字号 10:
bash
textutil -convert rtf -font Times -fontsize 10 {{foo.txt}}
  • 加载当前目录中的所有 RTF 文件,连接其内容,并将结果作为 index.html 写入,HTML 标题设置为"多个文件":
bash
textutil -cat {{html}} -title "多个文件" -output {{index.html}} *.rtf

xsltproc(macOS) · 用 XSLT 转换 XML 以生成输出(通常是 HTML 或 XML) ​

更多信息:https://manned.org/xsltproc。

  • 使用特定的 XSLT 样式表转换 XML 文件:
bash
xsltproc --output {{输出.html}} {{样式表.xslt}} {{xml 文件.xml}}
  • 将值传递给样式表中的参数:
bash
xsltproc --output {{输出.html}} --stringparam "{{键名}}" "{{值}}" {{样式表.xslt}} {{xml 文件.xml}}

示例整理自 tldr-pages,作者为 tldr-pages team and contributors,遵循 CC BY 4.0。

继续阅读