How to Use awk to Print All Columns After Specific Number


Often you may want to use awk to print all columns in a file after a specific number.

You can use the following syntax to do so:

awk '{s=""; for (i=2; i <= NF; i++) s=s $i " "; print s}' player_stats.txt

This particular example prints all fields after and including column 2 of the text file named player_stats.txt.

Note that this syntax uses a for loop to print each column in the file ranging from column 2 to column NF, which stands for “number of fields” and extracts the last field in a file.

By using this approach, we’re able to print all fields after and including column 2.

The following example shows how to use this syntax in practice.

Example: Use awk to Print All Columns After Specific Number

Suppose we have the following text file named player_stats.txt that contains information about statistics for various basketball players:

Suppose that we would like to print all fields after and including column 2 (the “points” column) of the file.

We can use the following syntax to do so:

awk '{s=""; for (i=2; i <= NF; i++) s=s $i " "; print s}' player_stats.txt

The following screenshot shows how to use this syntax in practice:

awk print all columns after

Notice that this prints all fields in the file after and including column 2.

Feel free to change i=2 to a different number in the for loop to instead print all columns after a different specific number.

Related Tutorials

The following tutorials explain how to perform other common tasks in awk:

How to Use awk to Print Rows Where Column Equals Value
How to Use awk to Print a Range of Columns
How to Use awk to Print All Fields Except First Field

Leave a Reply