From Pattern Recognition to Data Manipulation: The Versatility of AWK in Linux

Discover the unlimited possibilities of AWK for text processing in Linux/Unix! From pattern recognition to data manipulation – learn how to efficiently complete your tasks with this powerful command. Dive into the world of AWK and optimize your text processing tasks today!

Functionalities of AWK:

  • Scanning files line by line
  • Splitting each input line into fields
  • Comparing input lines and fields to patterns
  • Executing specific actions on matching lines

Usefulness of the AWK command:

  • Modifying data files
  • Creating formatted reports

Programming concepts for the AWK command:

  • Formatting output lines
  • Conditions and loops
  • Arithmetic and string operations

AWK Syntax:

The syntax of the AWK command is:

$ awk options 'selection_criteria {action}' input_file > output_file

To demonstrate AWK usage, we use the text file “file.txt”, where the first column is “Item”, the second column is “Model”, the third column is “Country”, and the fourth column is “Cost”.

AWK Command Examples:

Printing specific columns:

$ awk '{print $2 "\t" $3}' file.txt

Output:

BMW    Germany
Volvo  Sweden
Subaru Japan
Ferrari Italy
SAAB   USA

Printing all lines in a file:

Output:

1 BMW Germany 25000
2 Volvo Sweden 15000
3 Subaru Japan 2500
4 Ferrari Italy 2000000
5 SAAB USA 3000

Printing lines matching a specific pattern:

$ awk '/PATTERN/{print $0}' file.txt

Example:

$ awk '/o/ {print $0}' file.txt

Output:

2 Volvo Sweden 15000
5 SAAB USA 3000 

Printing columns matching a specific pattern:

$ awk '/PATTERN/{print $3 "\t" $4}' file.txt

Example:

$ awk '/a/ {print $3 "\t" $4}' file.txt

Output:

Counting and printing matching patterns:

$ awk '/PATTERN/{++cnt} END {print "Count = ", cnt}' file.txt

Example:

$ awk '/a/{++cnt} END {print "Count = ", cnt}' file.txt

Output:

Printing lines with more or less than a specified number of characters:

$ awk 'length($0) > 20' file.txt

Output:

1 BMW Germany 25000
2 Volvo Sweden 15000
3 Subaru Japan 2500
4 Ferrari Italy 2000000
5 SAAB USA 3000

Saving AWK output to another file:

$ awk '/PATTERN/{print $3 "\t" $4}' file.txt > Output.txt

Example:

$ awk '/a/ {print $3 "\t" $4}' file.txt > Output.txt

Conclusion:

AWK is another simple programming script that you can use to manipulate text in documents or perform specific functions. The commands shared here are only a few of many you can discover. With AWK, you have a powerful tool to automate and simplify your text processing tasks in Linux/Unix environments.

 

You might also be interested in:

Practical Tips for Converting Strings in C++

Overcoming Language Barriers: Integrating C Functionality into Python Applications

HttpClient: Making HTTP Requests in Java Applications Easy and Explained

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: