Linux – awk Command

The awk command is a versatile and powerful text processing tool that allows you to search, extract, and manipulate data from text files or input streams. It uses pattern matching and can perform complex text transformations.



Tutorials dojo strip

Initial Example

Using awk to print the first column of a file called data.txt:




AWK Parameters

ParameterDescription
-F sepstringSet the input field separator to sepstring. Equivalent to -v FS=sepstring. If both -F and -v are used, the order of FS assignment is unspecified.
-f progfileUse the file specified by progfile as the source of the awk program. A pathname of - denotes standard input. Multiple -f options concatenate the specified files as the program.
-v assignmentPre-assign the variable assignment before running the awk program, including BEGIN patterns. This can be used multiple times to set several variables.




Examples

1. Print Specific Columns

To print specific columns from a file:

awk '{print $1, $3}' filename.txt

2. Filter and Print Lines Matching a Pattern

To print lines that match a specific pattern:

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

3. Perform Calculations on Columns

To perform calculations on columns and print the result:

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

4. Use Field Separators

To specify a custom field separator, use the -F option. For example, if the file uses commas as separators:

awk -F, '{print $1, $2}' filename.txt

5. Print Line Numbers

To print line numbers along with the content:

awk '{print NR, $0}' filename.txt

6. Use Variables

To use variables in an awk script:

awk '{x = $1 + $2; print x}' filename.txt

7. Use Built-in Functions

To use built-in functions, such as length to print the length of each line:

awk '{print length($0)}' filename.txt




Linux Playground

Scroll to Top