我不确定为什么这不起作用。这是正则表达式'text\' => '.*?'
,我希望使用grep或sed在以下讨厌的文本中捕获estrenos
和cine
。这是我在grep中尝试的内容
echo "sadsa d{ 'text' => 'cine', 'indices' => [ 111, 116 ] }, { 'text' => 'estrenos', 'indices' => [ sSADW" | grep -Eo "'text\' => '.*?',"
答案 0 :(得分:3)
只需使用awk:
$ awk -v RS='}' -F\' '{print $4}' file
cine
estrenos
这适用于任何UNIX机器上任何shell中的任何awk。无论白色空间是什么,它都可以工作,无论您的输入是在一条线上还是分布在多条线上,无论每条线上的任何位置出现多少个空白或制表符,它都能正常工作。
以下是它的工作原理:
awk将所有输入视为分隔为字段的记录。您的输入(压缩空间以便于阅读):
sadsa d{ 'text' => 'cine', 'indices' => [ 111, 116 ] }, { 'text' => 'estrenos', 'indices' => [ sSADW
显然有{ ... }
条记录:
记录1:
{ 'text' => 'cine', 'indices' => [ 111, 116 ] }
记录2:
{ 'text' => 'estrenos', 'indices' => [ sSADW
所以我们可以将记录分隔符设置为}
(-v RS='}'
)。我假设你的最后一条记录真的会以}
结尾,但如果它没有那么好,因为awk将文件结尾视为记录的结尾。我们可以忽略{
之前的文本(即" sadsa d"在第一个记录之前和#34;"在2个记录之间 - 这真的被对待了作为第一个字段的一部分,但我们并未将该字段用于任何内容,因此它无关紧要。
因此,如果我们将它们分成每个'
(带-F\'
)的字段,则给出以上2条记录,然后我们得到:
$ awk -v RS='}' -F\' '{for (i=1; i<=NF;i++) print "Record Nr", NR, "Field Nr", i, "Field Contents: <" $i ">"; print "----"
}' file
Record Nr 1 Field Nr 1 Field Contents: <sadsa d{ >
Record Nr 1 Field Nr 2 Field Contents: <text>
Record Nr 1 Field Nr 3 Field Contents: < => >
Record Nr 1 Field Nr 4 Field Contents: <cine>
Record Nr 1 Field Nr 5 Field Contents: <, >
Record Nr 1 Field Nr 6 Field Contents: <indices>
Record Nr 1 Field Nr 7 Field Contents: < => [ 111, 116 ] >
----
Record Nr 2 Field Nr 1 Field Contents: <, { >
Record Nr 2 Field Nr 2 Field Contents: <text>
Record Nr 2 Field Nr 3 Field Contents: < => >
Record Nr 2 Field Nr 4 Field Contents: <estrenos>
Record Nr 2 Field Nr 5 Field Contents: <, >
Record Nr 2 Field Nr 6 Field Contents: <indices>
Record Nr 2 Field Nr 7 Field Contents: < => [ sSADW
>
----
因此您可以看到所需的值始终只是每条记录的第4个字段。
答案 1 :(得分:0)
删除单引号的转义字符。但是,由于扩展的正则表达式不支持非贪婪匹配,您可能希望改为使用Perl:
grep -Po "'text' => '.*?',
答案 2 :(得分:0)
tr + sed 方法:
(假设您的输入文本位于变量String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
)
$s
输出:
sed -n "s/.*'text' => '\([^']*\)'.*/\1/p" <(tr ',' '\n' <<< "$s")