在shell脚本中使用正则表达式

Ama*_*osh 24 regex linux shell

在linux shell脚本中使用正则表达式解析字符串的正确方法是什么?我写了下面的脚本来使用curl和在控制台上打印我的SO代表sed(并不仅仅是因为我反复疯狂 - 我在尝试学习一些shell脚本和正则表达式之前切换到linux).

json=$(curl -s http://stackoverflow.com/users/flair/165297.json)
echo $json | sed 's/.*"reputation":"\([0-9,]\{1,\}\)".*/\1/' | sed s/,//
Run Code Online (Sandbox Code Playgroud)

但不知何故,我觉得这sed不适合在这里使用.我听说这grep是关于正则表达式并且稍微探讨了一下.但显然它会在找到匹配时打印整行 - 我试图从单行文本中提取一个数字.这是我正在处理的字符串的缩小版本(返回curl).

{"displayName":"Amarghosh","声誉":"2,737","badgeHtml":"\ u003cspan title = \"1银徽章\"\ u003e\u003cspan class = \"badge2 \"\ u003e●\u003c/span\u003e\u003cspan class = \"badgecount \"\ u003e1\u003c/span\u003e\u003c/span\u003e"}

我想我的问题是:

  • 在linux shell脚本中使用正则表达式解析字符串的正确方法是什么?
  • sed在这里使用是正确的吗?
  • 这可以用grep吗?
  • 还有其他命令更容易/更合适吗?

pax*_*blo 12

grep命令将从许多行中选择所需的行,但不会直接操作该行.为此,您sed在管道中使用:

someCommand | grep 'Amarghosh' | sed -e 's/foo/bar/g'
Run Code Online (Sandbox Code Playgroud)

或者,可以使用awk(或者perl如果可用的话).它是一个比sed我认为更强大的文本处理工具.

someCommand | awk '/Amarghosh/ { do something }'
Run Code Online (Sandbox Code Playgroud)

对于简单的文本操作,只需坚持使用grep/sed组合.当您需要更复杂的处理时,请继续前进awkperl.

我的第一个想法就是使用:

echo '{"displayName":"Amarghosh","reputation":"2,737","badgeHtml"'
    | sed -e 's/.*tion":"//' -e 's/".*//' -e 's/,//g'
Run Code Online (Sandbox Code Playgroud)

它将sed进程数保持为一(你可以给多个命令-e).


小智 8

您可能有兴趣使用Perl执行此类任务.作为演示,这里是一个打印您想要的数字的Perl脚本:

#!/usr/local/bin/perl
use warnings;
use strict;
use LWP::Simple;
use JSON;

my $url = "http://stackoverflow.com/users/flair/165297.json";
my $flair = get ($url);
my $parsed = from_json ($flair);
print "$parsed->{reputation}\n";
Run Code Online (Sandbox Code Playgroud)

此脚本要求您安装JSON模块,您只需使用该命令即可cpan JSON.


Tör*_*bor 5

对于在shell脚本中使用JSON工作,使用jsawk其中如awk,但对于JSON.

json=$(curl -s http://stackoverflow.com/users/flair/165297.json)
echo $json | jsawk 'return this.reputation' # 2,747
Run Code Online (Sandbox Code Playgroud)