csdnceshi62 2011-02-22 16:34 采纳率: 100%
浏览 295
已采纳

如何使用 GREP、 REGEX 或 PERL 提取模式下的字符串

I have a file that looks something like this:

<table name="content_analyzer" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
  <type="global" />
</table>

I need to extract anything within the quotes that follow "name=", i.e., content_analyzer , content_analyzer2 and content_analyzer_items.

I am doing this on a Linux box, so a solution using sed, perl, grep or bash is fine.

转载于:https://stackoverflow.com/questions/5080988/how-to-extract-string-following-a-pattern-with-grep-regex-or-perl

  • 写回答

8条回答 默认 最新

  • 关注

    Since you need to match content without including it in the result (must match name=" but it's not part of the desired result) some form of zero-width matching or group capturing is required. This can be done easily with the following tools:

    Perl

    With Perl you could use the n option to loop line by line and print the content of a capturing group if it matches:

    perl -ne 'print "$1\n" if /name="(.*?)"/' filename
    

    GNU grep

    If you have an improved version of grep, such as GNU grep, you may have the -P option available. This option will enable Perl-like regex, allowing you to use \K which is a shorthand lookbehind. It will reset the match position, so anything before it is zero-width.

    grep -Po 'name="\K.*?(?=")' filename
    

    The o option makes grep print only the matched text, instead of the whole line.

    Vim - Text Editor

    Another way is to use a text editor directly. With Vim, one of the various ways of accomplishing this would be to delete lines without name= and then extract the content from the resulting lines:

    :v/name=/d
    :%s/\v.*name\="([^"]+)".*/\1
    

    Standard grep

    If you don't have access to these tools, for some reason, something similar could be achieved with standard grep. However, without the look around it will require some cleanup later:

    grep -o 'name="[^"]*"' filename
    

    A note about saving results

    In all of the commands above the results will be sent to stdout. It's important to remember that you can always save them by piping it to a file by appending:

    > result
    

    to the end of the command.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误