如何为此编写正则表达式?

How to write a regex for this?

要求:仅grep/cut/join/regex.

我有这样的数据:

  798 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
15386 /usr/bin/nautilus --gapplication-service
16051 /usr/bin/zeitgeist-daemon

我想从数字中提取行数据到第二个结尾space,比如

798 /usr/bin/dbus-daemon

只使用 grep/cut/join 有或没有正则表达式。

我试过了

grep -oe "[^ ][^ ]*  *[a-zA-Z\]*$"

但结果并不如预期。

您可以使用

# With GNU grep:
grep -oP '^\s*\K\S+\s+\S+' <<< "$s"
# With a POSIX ERE pattern:
grep -oE '[0-9][^ ]* +[^ ]+' <<< "$s" 

online demo

  • o - 匹配输出模式(不是行)
  • P - PCRE 正则表达式引擎用于解析模式

PCRE模式详情:

  • ^ - 行首
  • \s* - 0+白spaces
  • \K - 匹配重置运算符丢弃到目前为止匹配的整个文本
  • \S+ - 1+ 个非白色space 个字符
  • \s+\S+ - 1+ 白色space 和 1+ 非白色space 字符。

POSIX ERE 模式匹配

  • [0-9] - 一个数字
  • [^ ]* - space
  • 以外的 0+ 个字符
  • + - 1 个或多个 spaces
  • [^ ]+ - 除了 space.
  • 以外的 1+ 个字符