简体   繁体   English

awk正则表达式最后出现的字符/模式

[英]awk regex last occurence of character/pattern

I need to get the index of the last occurrence of a pattern. 我需要获取模式最后一次出现的索引。 Tried ideas from here and here . 这里这里尝试了一些想法。 The below does not work if I want the index of the last : (index is 6). 如果我想要最后一个的索引,则以下内容不起作用:索引为6)。 Tried to use the anchor $ but clearly have not grasped it (since it gives me the first occurrence, ie 3). 试图使用锚$但显然没有抓住它(因为它给了我第一次出现,即3)。 Explanations really appreciated. 解释真的很感激。

echo 12:45:78 | 
awk '
{
print match($1, /:.+$/)
}'

There is no need to use any regex here as awk allows you split file using a delimiter. 这里不需要使用任何正则表达式,因为awk允许您使用分隔符分割文件。

After using : as input field separator subtract last field's length from total line length to get right index like this: 使用后:作为输入字段分隔符从总行长度中减去最后一个字段的长度,得到正确的索引,如下所示:

awk -F: '{print length($0) - length($NF)}' <<< '12:45:78'

6

More examples: 更多例子:

awk -F: '{print length($0) - length($NF)}' <<< '12:45:78111:123'
12

awk -F: '{print length($0) - length($NF)}' <<< '12:45:78:123'
9

awk -F: '{print length($0) - length($NF)}' <<< '12:45'
3

awk -F: '{print length($0) - length($NF)}' <<< '12:'
3

You need to use 你需要使用

/:[^:]*$/

Here, [^:]* (a [^...] is a negated bracket expression ) will match 0+ chars other than : , so, only the last : is matched with the first : . 在此, [^:]* (一个[^...]是一个否定的括号表达式 )将匹配比其他 0+字符: ,所以,只有最后:与所述第一匹配:

Note this idea is almost right for you, the only difference being the quantifier: if you use + with [^:] , you won't match the : that is at the very end of the input string. 注意这个想法几乎适合你,唯一的区别是量词:如果你使用+[^:] ,你将不匹配:在输入字符串的最后。 Thus, * is the quantifier you want. 因此, *是您想要的量词。

Pattern details : 图案细节

  • : - a : followed with... : - a :紧随其后......
  • [^:]* - any 0+ chars other than : [^:]* - 除以下之外的任何0+字符:
  • $ - end of string. $ - 结束字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM