linux - 有没有办法在手册页中查找标志?

标签 linux bash unix sh less-unix

我正在尝试想出一种在手册页中查找特定标志的方法。通常,我输入“/” 搜索某些内容,然后使用“-Werror”之类的内容来查找特定标志。 问题是虽然有手册页(gcc 是现在激励我的那个) 在他们的文本中有很多对标志的引用,所以出现了很多次。

这没什么大不了的,但也许可以做得更好一些。我想找 类似于 '-O\n' 但它不起作用(可能是因为 man 程序不使用 C 转义符?) 然后我尝试了类似 man gcc | grep $'-O\n',因为我有点记得 以美元符号开头的单引号字符串具有 bash 解释常见的 C 转义... 它没有用,grep 回应了整个手册页。

这就是将我带到这里的原因:为什么?或者更确切地说,这可以做到吗?

最佳答案

rici's helpful answer很好地解释了原始方法的问题。

不过,还有一点值得一提:

man 的输出包含格式化控制字符,这会干扰文本搜索

如果您在搜索之前通过管道传输到 col -b,这些控制字符将被删除 - 请注意搜索结果也将是纯文本的副作用。 p>

但是,grep 不是这项工作的正确工具;我建议如下使用 awk 来获取 -O 的描述:

man gcc | col -b | awk -v RS= '/^\s+-O\n/'
  • RS=(一个空的输入记录分隔符)是一个 awk 习惯用法,它将输入分成非空行 block ,因此在这样一个 block 的开头匹配选项可确保 < em>返回包含选项描述的所有行。

如果你有一个 POSIX-features-only awk 比如 BSD/OSX awk,使用这个版本:

man gcc | col -b | awk -v RS= '/^[[:blank:]]+-O\n/'

显然,这样的命令输入起来有些麻烦,所以找到下面的通用bash函数manopt,它返回描述从其 man 页面 中指定命令的指定选项。 (可能会有误报和漏报,但总体来说效果很好。)

例子:

manopt gcc O          # search `man gcc` for description of `-O`
manopt grep regexp    # search `man grep` for description of `--regexp`
manopt find '-exec.*' # search `man find` for all actions _starting with_ '-exec'

bash 函数 manopt() - 放置在 ~/.bashrc 中,例如:

# SYNOPSIS
#   manopt command opt
#
# DESCRIPTION
#   Returns the portion of COMMAND's man page describing option OPT.
#   Note: Result is plain text - formatting is lost.
#
#   OPT may be a short option (e.g., -F) or long option (e.g., --fixed-strings);
#   specifying the preceding '-' or '--' is OPTIONAL - UNLESS with long option
#   names preceded only by *1* '-', such as the actions for the `find` command.
#
#   Matching is exact by default; to turn on prefix matching for long options,
#   quote the prefix and append '.*', e.g.: `manopt find '-exec.*'` finds
#   both '-exec' and 'execdir'.
#
# EXAMPLES
#   manopt ls l           # same as: manopt ls -l
#   manopt sort reverse   # same as: manopt sort --reverse
#   manopt find -print    # MUST prefix with '-' here.
#   manopt find '-exec.*' # find options *starting* with '-exec'
manopt() {
  local cmd=$1 opt=$2
  [[ $opt == -* ]] || { (( ${#opt} == 1 )) && opt="-$opt" || opt="--$opt"; }
  man "$cmd" | col -b | awk -v opt="$opt" -v RS= '$0 ~ "(^|,)[[:blank:]]+" opt "([[:punct:][:space:]]|$)"'
}

fish manopt() 的实现:

贡献者Ivan Aracki .

function manopt 
  set -l cmd $argv[1]
  set -l opt $argv[2] 
  if not echo $opt | grep '^-' >/dev/null
    if [ (string length $opt) = 1 ] 
      set opt "-$opt"
    else
      set opt "--$opt"
    end
  end
  man "$cmd" | col -b | awk -v opt="$opt" -v RS= '$0 ~ "(^|,)[[:blank:]]+" opt "([[:punct:][:space:]]|$)"'
end

关于linux - 有没有办法在手册页中查找标志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198721/

相关文章:

c - Linux 内核模块原子模式

linux - 如何设置 Gitlab 钩子(Hook)来验证 git 推送到远程

linux - 如何检测何时从键绑定(bind)触发 bash 脚本

mysql - Amazon RDS 内存不足

bash - 命令行批量重命名

python - 通过 Python Popen 运行长时间运行的进程

linux - 在 linux 中遍历两个文件 ||列比较

c - 如何更改 linux 终端中的回显字符

bash - 持续运行 bash 脚本

c++ - 无法使用 Fedora 中的 g++