【问题标题】:grep that returns string between " characters返回 " 字符之间的字符串的 grep
【发布时间】:2014-03-30 13:56:20
【问题描述】:

我有一个看起来像这样的文件:

Data.s "intro.png"
Data.s "extended.png"
Data.s "animationen.png"
Data.s "buttons.png"

我需要一个,它只返回" 字符内的字符串。

我试过了:

grep '"(.*)"' filename

那什么也不返回。 当我删除括号时,我得到了匹配的每一行 我只需要" 字符内的字符串。

【问题讨论】:

    标签: grep linux command-line grep


    【解决方案1】:

    使用 GNU grep

    grep -oP '(?<=").*?(?=")' file
    intro.png
    extended.png
    animationen.png
    buttons.png
    

    【讨论】:

      【解决方案2】:

      您可以使用awk

      awk -F\" '/Data.s/ {print $2}' file
      intro.png
      extended.png
      animationen.png
      buttons.png
      

      【讨论】:

      • 该文件还包含与上面的行不同的行。像空行和 cmets。我将如何排除这些?
      • @MarkusDöbele 那么你应该在你的帖子中发布。已更新我的帖子,仅在行包含 Data.s 时才提供输出
      • @MarkusDöbele,您应该首先澄清您帖子中的所有内容。这将有助于人们给出最佳答案。
      【解决方案3】:

      grep 不支持立即捕获组。
      您通常需要使用 -P 标志,它会为 grep 开启 Perl RegExp 引擎。

      由于 1_CR 已经提到了这个选项,我将提到一个不同的工作工具。

      sed

      $ sed 's/^.*"\(.*\)"$/\1/' /tmp/so.txt
      

      将 /tmp/so.txt 替换为适当的文件路径。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-04
        • 1970-01-01
        • 1970-01-01
        • 2019-08-18
        • 1970-01-01
        • 1970-01-01
        • 2014-12-08
        相关资源
        最近更新 更多