Table of Contents
1. Introduction
awk is interpreted programming language. It is very powerful and used for text processing. Awk stands for the names of its authors “Aho, Weinberger, and Kernighan”.
One of its fundamental features is the ability to easily extract specific columns from a text input. The command awk print $1
is used for this purpose. It prints the first field (or column) from each line of a given input.
2. Understanding awk print $1
The awk print $1
command is used to extract the first column(or field) of data from a text input.
Let’s see with the help of example:
1 2 3 |
echo "Hello world from Java2blog" | awk '{print $1}' |
1 2 3 |
Hello |
awk '{print $1}'
tells awk to execute the print action, where$1
refers to the first field (or column) of the input.- By default, awk considers spaces and tabs as field separators.
Awk actually uses some variables for each data field found as below:
- $0 for whole line
- $1 for first field
- $2 for second field
- $3 for third field
- $n for nth field
So here, print $1
represents the first field of the input.
3. Changing the Field Separator
In scenarios where data is not space-delimited, we can provide custom delimiter with -F
flag.
Let’s understand with the help of an example:
1 2 3 |
echo "India, China, Bhutan, Russia" | awk -F',' '{print $1}' |
1 2 3 |
India |
-F','
sets the field separator to a comma, and $1
then refers to the data before the first comma.
4. Printing Multiple Fields
To print multiple fields, we can include multiple field identifiers in the print action.
1 2 3 |
echo "India, China, Bhutan, Russia" | awk -F',' '{print $1, $4}' |
1 2 3 |
India Russia |
{print $1, $4}
prints first and fourth fields.
5. Using awk print $1 with Files
awk command can process file input directly, making it easier to use it with files.
Let’s read a csv file and prints its first column:
1 2 3 |
awk -F',' '{print $1}' countries.csv |
This prints first field of each line of comma delimited csv file.
6. Combining awk with Other Commands
In practice, awk
is often combined with different other commands to get desired output.
Here is one example of such command:
1 2 3 |
cat file.txt | awk '{print $1}' | sort | uniq |
This commands extracts first field of file.txt, sort it, and filter out duplicate values.
7. Conclusion
awk print $1
is a fundamental command in text processing for Unix and Linux users. It’s simple yet powerful, capable of handling a wide range of data extraction tasks.
By changing the field separator and combining awk with other commands, you can manipulate and extract data from text inputs effectively. Whether you’re dealing with log files, CSVs, or any structured text data, awk print $1
and its variations offer a versatile solution for your scripting needs.