如何提取man手册中工具的NAME与DESCRIPTION完整内容?
提取man手册的NAME和DESCRIPTION章节
直接用这条命令就能搞定,适配绝大多数标准man手册:
man <工具名> | col -bx | awk '/^NAME$/{flag=1; print; next} /^DESCRIPTION$/{flag=1; print; next} /^[A-Z][A-Z ]+$/ && flag{exit} flag'
命令拆解:
col -bx:清理man输出里的控制字符(比如反向换行、下划线控制码),把文本转换成正常的纯文本格式,避免后续awk匹配出错。- awk逻辑:
- 匹配到整行是
NAME的行时,开启输出标记flag,打印该行后跳过下一行处理。 - 匹配到整行是
DESCRIPTION的行时,同样开启标记并打印。 - 当标记开启时,如果遇到其他全大写的章节标题(比如
SYNOPSIS、OPTIONS这类),就退出awk,停止输出——因为这意味着NAME和DESCRIPTION章节已经结束。 - 只要标记
flag为1,就打印当前行,也就是输出两个章节的内容。
- 匹配到整行是
示例:
以ls为例,运行:
man ls | col -bx | awk '/^NAME$/{flag=1; print; next} /^DESCRIPTION$/{flag=1; print; next} /^[A-Z][A-Z ]+$/ && flag{exit} flag'
输出格式就是你要的:
NAME ls – list directory contents DESCRIPTION For each operand that names a file of a type other than directory, ls displays its name as well as any requested, associated information. For each operand that names a file of type directory, ls displays the names of files contained within that directory, as well as any requested, associated information.
特殊情况适配:
如果遇到部分man手册的章节标题前后带空格(比如 NAME ),可以把awk里的匹配正则改成/^[[:space:]]*NAME[[:space:]]*$/和/^[[:space:]]*DESCRIPTION[[:space:]]*$/,确保能匹配到标题行。
内容的提问来源于stack exchange,提问作者DontPanic
相关产品推荐
相关产品推荐

