Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decipher the regular expression

Tags:

regex

awk

please help me decipher the regular expression-

'!_[$0]++'

It is being used to get a MSISDN (one at a time from a file containing list of MSISDN starting with zero )by the following usage:

awk '!_[$0]++' file.txt
like image 745
user2688459 Avatar asked Aug 25 '26 02:08

user2688459


2 Answers

It's not a regular expression, it's an arithmetic and boolean expression.

  • $0 = The current input line
  • _[$0] = An associative array element whose key is the input line
  • _[$0]++ = increment that array element each time we encounter a repeat of the line, but evaluates to the original value
  • !_[$0]++ = boolean inverse, so it returns true if the value was originally 0 or the empty string, false otherwise

So this expression is true the first time a line is encountered, false every other time. Since there's no action block after the expression, the default is to print the line if the expression is true, skip it when false.

So this prints the input file with duplicates omitted.

like image 78
Barmar Avatar answered Aug 26 '26 21:08

Barmar


'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.

So all the duplicate lines will not be prited.

like image 39
Vijay Avatar answered Aug 26 '26 19:08

Vijay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!