【问题标题】:Cut specific words matching a pattern from a text file从文本文件中剪切与模式匹配的特定单词
【发布时间】:2015-05-20 08:10:37
【问题描述】:

我正在尝试使用 shell 脚本从匹配模式的文本文件中提取单词。例如,如果一行包含

This is a sample text to illustrate my scenario text=info id=2342
Second line to illustrate text=sample id=q2312

我希望输出像

text=info id=2342
text=sample id=q2312

谁能告诉我如何使用 cut/grep 命令实现它?

【问题讨论】:

    标签: shell grep cut


    【解决方案1】:

    您可以执行以下操作:

    grep -P -o 'text=\S+ id=\S+'

    grep-P 标志启用 perl 正则表达式。 \S+ 将匹配所有非空格字符,-o 仅输出匹配的部分。

    假设您需要获取字段“text”和“id”值。根据需要修改正则表达式。 perl 正则表达式见here 或扩展正则表达式见man grep

    【讨论】:

      【解决方案2】:

      这个grep -oP 应该可以工作:

      grep -oP '\b(\w+=\w+(\s+|$))+' file
      text=info id=2342
      text=sample id=q2312
      

      【讨论】:

      • 嗨,anubhava,这似乎对 mrezzaaa 的要求有效。但是请您稍微解释一下 grep 中使用的 reg-ex。
      • \w+ 匹配一个单词,其中\b 是单词边界。 \w+=\w+ 匹配由 = 分隔的 2 个单词,后跟 (\s+|$) 其中 1+ 空格或行尾。 (\w+=\w+(\s+|$))+ 将匹配多个由空格分隔的 name=value 对。
      【解决方案3】:

      使用 cut 您需要处理额外的内容(从第一个 = 剪切并添加文本 =):

      echo "text=$(echo "This is a sample text to illustrate my scenario text=info id=2342" | cut -d= -f2-)"
      

      使用 sed:

      echo "This is a sample text to illustrate my scenario text=info id=2342" | sed 's/.* text=/text=/'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-14
        • 1970-01-01
        • 2014-04-13
        • 2018-12-10
        • 2023-01-22
        • 1970-01-01
        • 2022-01-01
        • 2018-07-20
        相关资源
        最近更新 更多