Linux / Unix AWK: Read a Text File

 

In AWK, you can read a text file using the awk command followed by the { commands } block that specifies the actions to be performed on each line of the input file. The input file can be specified as the last argument on the command line, or it can be redirected from the standard input.

Here’s an example of how to use AWK to read and print the contents of a file named file.txt:

awk '{ print }' file.txt

In this example, the { print } block is a simple command that prints each line of the input file, as is.

AWK also provides several built-in variables that make it easier to process the contents of the input file. For example, the $0 variable holds the entire line, while the $1, $2, etc. variables hold the values of the individual fields within the line.

Here’s an example of how to use AWK to read a file containing tab-separated values and print only the first and third fields:

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

In this example, the print $1, $3 command prints the first and third fields of each line, separated by a space.

Note that the input file does not have to be a simple text file; it can be any kind of text-based data, including CSV files, log files, or configuration files, among others. The power of AWK lies in its ability to process and manipulate text-based data in a flexible and efficient manner.

Leave a Comment