bash Shell 相当于 PHP 的 preg_replace()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4490927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:08:17  来源:igfitidea点击:

Shell equivalent to PHP's preg_replace()

phpregexbashpreg-replaceunix

提问by seriousdev

Greetz folks.

问候各位。

I'm looking for a way to do the same stuff than PHP's preg_replace()does (search text matching a regular expression and replace it) in a shell script.

我正在寻找一种方法来在 shell 脚本中执行与 PHP 的preg_replace()相同的事情(搜索匹配正则表达式的文本并替换它)。

So, consider the following file.

因此,请考虑以下文件。

<a href="http://example.com/">Website #1</a>
<a href="http://example.net/">Website #2</a>
<a href="http://example.org/">Website #3</a>

And I want to get this:

我想得到这个:

http://example.com/
http://example.net/
http://example.org/

Is there a way to do this? Thanks.

有没有办法做到这一点?谢谢。

回答by codaddict

You can use sedas:

您可以sed用作:

sed -r 's/.*href="([^"]*)".*//' file

See it

看见

回答by Benoit Duffez

While sedis perfectly suitable, it doesn't allow more than 9 backreferences. Perl does:

虽然sed非常合适,但它不允许超过 9 个反向引用。Perl 做:

echo "a b c d e f g h i j k l m n o p q r s t u v w x y z" | \
    perl -lpe 's/(\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)/;;;;;;;;;;;;;;;;;;;;;;;;;/g'
a;b;c;d;e;f;g;h;i;j;k;l;m;n;o;p;q;r;s;t;u;v;w;x;y;z

This (dumb) example show it's possible to go further than sed's \9

这个(愚蠢的)例子表明有可能比sed's更进一步\9