Terminal - awk command

From NoskeWiki
Jump to navigation Jump to search

About

This page is a child of: Terminal commands


The awk command is a powerful tool for processing text files, particularly useful for manipulating data and generating reports. Named after its creators Aho, Weinberger, and Kernighan, AWK is an essential tool in Unix and Unix-like operating systems.

Overview

AWK is a domain-specific language designed for text processing and is typically used as a data extraction and reporting tool. It's a standard feature of most Unix-like operating systems and is mainly used for pattern scanning and processing.

Syntax

The basic syntax of the AWK command is:

awk [options] 'program' input-file1 input-file2 ...

The 'program' is a series of commands to be executed by AWK, which typically involve pattern matching and processing actions.

Features

  • Pattern Scanning: AWK reads through a file line by line, searching for lines that match a given pattern.
  • Text Processing: It processes text by performing actions on matched lines.
  • Built-in Variables: AWK has several built-in variables like FS (field separator), OFS (output field separator), NR (number of records), etc.
  • User-defined Variables: Users can define their own variables for processing.
  • Arrays: Supports arrays for complex data manipulation.
  • Control Flow Statements: Includes 'if', 'while', 'for', and other control flow statements.

Common Uses

  • Data Extraction: Extracting data from text files based on patterns.
  • Data Transformation: Transforming data formats, such as CSV to JSON.
  • Report Generation: Generating reports from log files or data files.
  • Text Processing: Performing complex text manipulations and analysis.

Examples

Here are some common examples of AWK usage:

Print the first column of a file

awk '{print $1}' filename

Sum a Column of Numbers

awk '{sum += $1} END {print sum}' filename


Links