AWK ward

AWK is a powerful programming language used for pattern scanning and processing. Here are some useful AWK tips and examples to help you get the most out of this tool:

Basic Syntax

AWK operates on files or input provided via pipes. Its basic syntax is:

awk 'pattern { action }' file

Printing Specific Fields

  1. Print the First Field:
   awk '{ print $1 }' file
  1. Print the First and Third Fields:
   awk '{ print $1, $3 }' file

Field Separator

  1. Specify a Different Field Separator:
   awk -F, '{ print $1 }' file

This example sets the field separator to a comma.

Pattern Matching

  1. Print Lines Containing a Specific Pattern:
   awk '/pattern/' file
  1. Print Lines Where the Second Field Equals a Value:
   awk '$2 == "value" { print $0 }' file

Built-in Variables

  1. NR (Record Number):
   awk '{ print NR, $0 }' file
  1. NF (Number of Fields):
   awk '{ print $1, NF }' file

Calculations

  1. Sum Values in a Column:
   awk '{ sum += $1 } END { print sum }' file
  1. Average of Values in a Column:
   awk '{ sum += $1; count++ } END { print sum/count }' file

Conditional Statements

  1. If-Else Statements:
    bash awk '{ if ($1 > 100) print $1, "High"; else print $1, "Low" }' file

Formatting Output

  1. Printf for Formatted Output:
    bash awk '{ printf "%-10s %-10s\n", $1, $2 }' file

Using AWK with Pipes

  1. AWK in a Pipeline:
    bash cat file | awk '{ print $1 }'

Working with Multiple Files

  1. Process Multiple Files:
    bash awk '{ print FILENAME, $0 }' file1 file2

String Operations

  1. Concatenate Strings:
    bash awk '{ print $1 $2 }' file
  2. String Length:
    bash awk '{ print length($1) }' file

AWK Functions

  1. Use Built-in Functions:
    bash awk '{ print toupper($1) }' file

Advanced Examples

  1. Count Occurrences of Each Word:
    bash awk '{ for (i=1; i<=NF; i++) count[$i]++ } END { for (word in count) print word, count[word] }' file
  2. Print Last Field of Each Line:
    bash awk '{ print $NF }' file

AWK Script

  1. Create an AWK Script File:
    Save the following content to a file named script.awk:
    awk { if ($1 > 100) { print $1, "High" } else { print $1, "Low" } }
    Run it with:
    bash awk -f script.awk file

Tips for Efficient Use

  1. Use Shortcuts:
    • awk '{ print $NF }' file prints the last field.
    • awk 'NF > 0' file skips empty lines.
    • awk 'BEGIN { print "Header" } { print } END { print "Footer" }' file adds a header and footer to the output.

By mastering these AWK tips and techniques, you can efficiently process and analyze text data from the command line.

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.