在bash(多行)中的两个单词之间获取文本

时间:2016-07-08 22:35:45

标签: string bash text get between

我正在与这个问题作斗争。我有这样的文字:

Executables:   manatee-curl
Dependencies:  base ==4.*, manatee-core >=0.1.1, dbus-client ==0.3.*,
               stm >=2.1.2.0, containers >=0.3.0.0, gtk >=0.12.0,
               text >=0.7.1.0, mtl >=1.1.0.2, old-time -any,
               old-locale -any, glib >=0.12.0, gio >=0.12.0,
               filepath >=1.1.0.3, utf8-string >=0.3.4, bytestring -any,
               network -any, curl >=1.3.7, directory -any,
               template-haskell -any, derive -any, binary -any,
               regex-tdfa -any, dbus-core -any
Cached:        No

我希望在“Dependencies:”和“Cached”之间获得所有这些词。 您可以将此文本视为变量,例如:

echo $ text | grep / dostuff /

要清楚,我想得到的输出是:

base ==4.*, manatee-core >=0.1.1, dbus-client ==0.3.*,
stm >=2.1.2.0, containers >=0.3.0.0, gtk >=0.12.0,
text >=0.7.1.0, mtl >=1.1.0.2, old-time -any,
old-locale -any, glib >=0.12.0, gio >=0.12.0,
filepath >=1.1.0.3, utf8-string >=0.3.4, bytestring -any,
network -any, curl >=1.3.7, directory -any,
template-haskell -any, derive -any, binary -any,
regex-tdfa -any, dbus-core -any

谢谢。

3 个答案:

答案 0 :(得分:0)

您可以使用sed在两种模式之间获取文字:

text=$(sed -n '/^Dependencies:/,/^Cached:/{$d;s/Dependencies: *//;p;}' file)

echo "$text"

base ==4.*, manatee-core >=0.1.1, dbus-client ==0.3.*,
               stm >=2.1.2.0, containers >=0.3.0.0, gtk >=0.12.0,
               text >=0.7.1.0, mtl >=1.1.0.2, old-time -any,
               old-locale -any, glib >=0.12.0, gio >=0.12.0,
               filepath >=1.1.0.3, utf8-string >=0.3.4, bytestring -any,
               network -any, curl >=1.3.7, directory -any,
               template-haskell -any, derive -any, binary -any,
               regex-tdfa -any, dbus-core -any

IDEOne Working Demo

答案 1 :(得分:0)

awk救援!

$ awk '/^Dependencies:/{$1="";p=1} /^Cached:/{p=0} p{sub(/^ +/,"");print}' file

base ==4.*, manatee-core >=0.1.1, dbus-client ==0.3.*,
stm >=2.1.2.0, containers >=0.3.0.0, gtk >=0.12.0,
text >=0.7.1.0, mtl >=1.1.0.2, old-time -any,
old-locale -any, glib >=0.12.0, gio >=0.12.0,
filepath >=1.1.0.3, utf8-string >=0.3.4, bytestring -any,
network -any, curl >=1.3.7, directory -any,
template-haskell -any, derive -any, binary -any,
regex-tdfa -any, dbus-core -any

您可以照常分配给变量

$ text=$(awk ...)

答案 2 :(得分:0)

使用GNU grep:

echo "$text" | grep -Poz 'Dependencies:  \K(.*\n)*(?=Cached:)' | grep -Po '^ +\K.*'

输出:

base ==4.*, manatee-core >=0.1.1, dbus-client ==0.3.*,
stm >=2.1.2.0, containers >=0.3.0.0, gtk >=0.12.0,
text >=0.7.1.0, mtl >=1.1.0.2, old-time -any,
old-locale -any, glib >=0.12.0, gio >=0.12.0,
filepath >=1.1.0.3, utf8-string >=0.3.4, bytestring -any,
network -any, curl >=1.3.7, directory -any,
template-haskell -any, derive -any, binary -any,
regex-tdfa -any, dbus-core -any

请参阅:The Stack Overflow Regular Expressions FAQ