使用 sed 从 `gem environment` 的输出中提取路径

Extract a path from the output of `gem environment` using sed

执行gem environmentreturns以下输出:

RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.7
  - RUBY VERSION: 1.8.7 (2010-08-16 patchlevel 302) [x86_64-linux]
  - INSTALLATION DIRECTORY: /var/lib/gems/1.8
  - RUBY EXECUTABLE: /usr/bin/ruby1.8
  - EXECUTABLE DIRECTORY: /var/lib/gems/1.8/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /var/lib/gems/1.8
     - /root/.gem/ruby/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/

使用 sed,如何具体提取 EXECUTABLE DIRECTORY 值以检索 /var/lib/gems/1.8/bin

我认为使用 sed 很难做到这一点,您基本上必须删除不包含 EXECUTABLE DIRECTORY 的每一行,然后删除其余的所有内容,直到冒号.

gem environment | sed '/EXECUTABLE DIRECTORY/!d;s/^.*: //'

为此我会推荐 awk

gem environment | awk -F': *' '/EXECUTABLE DIRECTORY/ {print }'

grep:

gem environment |  grep -Po 'EXECUTABLE DIRECTORY: \K.*'

您可以像这样使用管道将输出传输到 awk:

gem environment | awk -F ' *: *' ' ~ /EXECUTABLE DIRECTORY/{print }'
/var/lib/gems/1.8/bin