Tedee12345
Tedee12345

Reputation: 1210

AWK - request for clarification example

I have 3 examples of using gsub:

1.

echo -e "A A\nB B\nC C" | awk '{gsub($(!/B/),"",$1); print $1 "\t" $2}' 
    A
B   B
    C

2.

$ echo -e "A A\nB B\nC C" | awk '{gsub($(!/B/),"",$2); print $1 "\t" $2}'
A   
B   B
C   

3.

$ echo -e "A A\nB B\nC C" | awk '{gsub($(!/B/),"",$0); print $1 "\t" $2}'



.

Why in the 3 example awk nothing printed? Does awk should not print?:

B   B

Please explain 3 examples.

Thank you for your help.

Upvotes: 2

Views: 3373

Answers (1)

Birei
Birei

Reputation: 36262

The key point for me is this: $(!/B/). Very awkward. What does it mean (or at least I guess it means)?

  • /B/: It tries to match the letter B in the whole line. If it matches returns 1, otherwise 0.
  • !: Negates the previous result code.
  • $(): It returns the whole line ($0) or the first field ($1) after resolving previous instructions.

The third case is ok.

  • When B matches the instruction is gsub( $0, "", $0 ), an empty line. That's clear.
  • When B doesn't match the instruction is gsub( $1, "", $0 ). So, as both letters are the same and gsub replaces many times by line, it deletes all characters. Add another different character and you will see the difference.

For example:

echo -e "A A 1\nB B 1\nC C 1" | awk '{gsub($(!/B/),"",$0); print $1 "\t" $2}'

That yields:

1

1

Upvotes: 3

Related Questions