Linux awk Command

The awk command in Linux is a powerful text-processing tool used for pattern scanning and processing. It allows you to manipulate and analyze text files or streams efficiently.

Syntax

awk [options] 'pattern {action}' file

Options

Option Description
-F Specifies the input field separator.
-v Assigns a variable before execution.
--help Displays help information.
--version Displays the version of awk.

Examples

1. Print the first column of a file

awk '{print $1}' file.txt

This command prints the first column of each line in file.txt.

2. Use a custom field separator

awk -F: '{print $1}' /etc/passwd

This command uses : as the field separator and prints the first field of each line in the /etc/passwd file.

awk -F'[:;.]'' '{print $1}' /etc/passwd

This command uses multiple field separators (:, ;, and .) and prints the first field of each line in the /etc/passwd file.

awk  '{print $1}' FS=':' /etc/passwd

This command uses the FS variable to set the field separator to : and prints the first field of each line in the /etc/passwd file.

3. Print lines matching a pattern

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

This command prints all lines in file.txt that match the specified pattern.

4. Perform arithmetic operations

awk '{print $1, $2, $1 + $2}' file.txt

This command prints the first two columns and their sum for each line in file.txt.

5. To Replace a feild separators with another using OFS option

awk 'BEGIN -F':' '{print $1, $2}' OFS="--" file.txt

This command uses the BEGIN block to set the field separator to : and the output field separator to --, printing the first two fields of each line in file.txt.