3

请帮我破译正则表达式-

'!_[$0]++'

它被用于通过以下用法获取 MSISDN(一次从包含以零开头的 MSISDN 列表的文件中获取一个):

awk '!_[$0]++' file.txt
4

3 回答 3

6

它不是正则表达式,而是算术和布尔表达式。

  • $0= 当前输入线
  • _[$0]= 一个关联数组元素,其键是输入行
  • _[$0]++= 每次遇到重复行时增加该数组元素,但计算结果为原始值
  • !_[$0]++= boolean inverse,因此如果值最初为 0 或空字符串,则返回 true,否则返回 false

所以这个表达式在第一次遇到一行时为真,每隔一次就为假。由于表达式后面没有动作块,因此默认为如果表达式为真则打印该行,如果为假则跳过它。

所以这会打印省略重复的输入文件。

于 2013-08-16T07:13:25.447 回答
1

这不是正则表达式。这个特殊的命令在第一次找到它们时打印唯一的行。

_在这里用作数组并$0指代整行。鉴于数组元素的默认数值是0(它在技术上是一个空字符串,但在数值上下文中它被视为 0),当您第一次看到一行时,您打印该行(因为_[$0]是假的,所以!_[$0]将是真的)。该命令每看到一行就递增(打印后——awk的默认命令是打印),所以下次看到该行时_[$0]1和该行不打印

于 2013-08-16T07:13:14.870 回答
1
'true'- then the line will be printed

'_[$0]++'- associative array will be incremented everytime when $0 is present.means it will set the number of times each line is repeated.

'!_[$0]++'-this will be true when a line is inserted in the associative array for the firsttime only and the rest of the times it will resolve to false ultimately not printing the line.

所以所有重复的行都不会被打印。

于 2013-08-16T07:11:46.253 回答