【问题标题】:How to extract quoted string for the first place?如何首先提取带引号的字符串?
【发布时间】:2013-01-22 22:42:08
【问题描述】:

我有一个包含这些值的文件:-

<property name="india" column="delhi" />
<property name="austrelia" column="sydney" />
<property name="uae" column="dubai" />

现在我想在第一个“”中提取值。 所以结果应该是:-

india
austrelia
uae

我正在使用 shell,我的正则表达式是 "(.*?)" 。但它同时选择了“”值。我只想要第一个。 有人可以为此建议我正确的正则表达式吗?

【问题讨论】:

  • 也许我们必须澄清一些事情:您在什么情况下使用正则表达式? (它真的是在 shell 上还是 php 上?)你想对结果做什么以及你使用的是什么操作系统?

标签: regex shell pattern-matching


【解决方案1】:

试试这个:

sed -r 's/^[^"]+"([^"]*)".*/\1/' file

使用您的数据进行测试:

kent$  echo '<property name="india" column="delhi" />
<property name="austrelia" column="sydney" />
<property name="uae" column="dubai" />'|sed -r 's/^[^"]+"([^"]*)".*/\1/'
india
austrelia
uae

【讨论】:

  • 请注意,在 Mac OSX 上,使用正则表达式模式的选项是 -E 而不是 -r
  • @Simon 好评。我有 0 的 Mac OS 经验。但是如果你安装了 gnu sed,选项应该是一样的吧?
【解决方案2】:
$ awk -F\" '{print $2}' file

顺便说一句,shell 可能不是解析 XML 的理想工具。

【讨论】:

    猜你喜欢
    • 2011-03-18
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    相关资源
    最近更新 更多