-1

Could someone explain to me what this part: ~/[bcdfg]/) of the following code:

awk ' {for(i=1;i<=NF;i++) {if ($i ~/[bcdfg]/) count++;

means? I know that it counts how often b,c,d,f appear but I don't understand how it's working. What does "~" exactly do and also I don't understand how this part [bcdfg]/) works.

1
  • 2
    Use the GNU awk user guide. The tilde is a regular expression match, and the text between slashes is a regular expression. By the way, this code counts the number of fields*g that contain one of these letters; it does not count the number of **letters. – berndbausch Mar 25 at 0:03
4

~ is the "regular expression matching" operator. It takes the string on the left-hand side and compares it to the regular expression pattern on the right hand side. See Regexp Usage

/.../ specifies a regular expression literal -- see Regular Expressions

[bcdfg] is a regular expression bracket expression: it matches against a single character, one of b, c, d, f, g -- see Using Bracket Expressions

This pattern is not anchored, so it is testing if $i contains one of the specified letters.

1
  • @berndbausch I didn't see you comment (somehow) before I wrote my answer. Sorry for stealing your thunder. – glenn jackman Mar 25 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.