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
- Print the First Field:
awk '{ print $1 }' file
- Print the First and Third Fields:
awk '{ print $1, $3 }' file
Field Separator
- Specify a Different Field Separator:
awk -F, '{ print $1 }' file
This example sets the field separator to a comma.
Pattern Matching
- Print Lines Containing a Specific Pattern:
awk '/pattern/' file
- Print Lines Where the Second Field Equals a Value:
awk '$2 == "value" { print $0 }' file
Built-in Variables
- NR (Record Number):
awk '{ print NR, $0 }' file
- NF (Number of Fields):
awk '{ print $1, NF }' file
Calculations
- Sum Values in a Column:
awk '{ sum += $1 } END { print sum }' file
- Average of Values in a Column:
awk '{ sum += $1; count++ } END { print sum/count }' file
Conditional Statements
- If-Else Statements:
bash awk '{ if ($1 > 100) print $1, "High"; else print $1, "Low" }' file
Formatting Output
- Printf for Formatted Output:
bash awk '{ printf "%-10s %-10s\n", $1, $2 }' file
Using AWK with Pipes
- AWK in a Pipeline:
bash cat file | awk '{ print $1 }'
Working with Multiple Files
- Process Multiple Files:
bash awk '{ print FILENAME, $0 }' file1 file2
String Operations
- Concatenate Strings:
bash awk '{ print $1 $2 }' file - String Length:
bash awk '{ print length($1) }' file
AWK Functions
- Use Built-in Functions:
bash awk '{ print toupper($1) }' file
Advanced Examples
- 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 - Print Last Field of Each Line:
bash awk '{ print $NF }' file
AWK Script
- Create an AWK Script File:
Save the following content to a file namedscript.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
- Use Shortcuts:
awk '{ print $NF }' fileprints the last field.awk 'NF > 0' fileskips empty lines.awk 'BEGIN { print "Header" } { print } END { print "Footer" }' fileadds 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.
Leave a Reply
You must be logged in to post a comment.