Using patterns and actions in AWK

In AWK, patterns and actions are used together to process input data. A pattern is a regular expression or condition that matches lines of input, and an action is a set of commands to be executed for each matching line. The basic syntax for an AWK program is:

pattern { action }

If the pattern matches the current line of input, the action is executed. If the pattern is omitted, the action is executed for every line of input. If the action is omitted, the default action is to print the entire line.

Here are some examples of using patterns and actions in AWK:

– Printing lines that match a pattern:

`
  awk '/pattern/ { print }' file.txt
  

This program prints every line of `file.txt` that contains the string “pattern”.

– Printing specific fields of matching lines:

`
  awk '/pattern/ { print $1, $3 }' file.txt
  

This program prints the first and third fields of every line of `file.txt` that contains the string “pattern”.

– Calculating statistics on matching lines:

`
  awk '/pattern/ { sum += $1 } END { print sum }' file.txt
  

This program calculates the sum of the first field of every line of `file.txt` that contains the string “pattern”, and prints the result at the end of processing.

– Using regular expressions to match patterns:

`
  awk'/^a/ { print }' file.txt
  

This program prints every line of `file.txt` that starts with the letter “a”.

– Using multiple patterns and actions:

`
  awk '/pattern1/ { action1 } /pattern2/ { action2 }' file.txt
  

This program executes `action1` for every line of `file.txt` that contains “pattern1”, and `action2` for every line that contains “pattern2”.

– Using logical operators to combine patterns:

`
  awk '/pattern1/ && /pattern2/ { print }' file.txt
  

This program prints every line of `file.txt` that contains both “pattern1” and “pattern2”.

– Using user-defined variables in actions:

`
  awk '{ sum += $1 } END { print "Sum is:", sum }' file.txt
  

This program calculates the sum of the first field of every line of `file.txt`, and prints the result with a message at the end of processing.

These are just a few examples of how patterns and actions can be used in AWK to process input data. The possibilities are endless, and you can use a combination of patterns, actions, and built-in functions to manipulate and transform data in a variety of ways.