How to Use awk to Print a Range of Columns


You can use the following syntax in awk to print a range of columns in a file:

awk -v f=2 -v l=4 'BEGIN{FS=OFS=" "} {for (i=f;i<=l;i++) printf "%s%s", $i, (i<l ? OFS : ORS)}' player_stats.txt

This particular example will print the columns in the range 2 through 4 of the text file named player_stats.txt.

The f variable specifies the “first” column to print and the l variable specifies the “last” column to print.

If you’d like to use shorter syntax, you can use the cut command to achieve the same result:

cut -d' ' -f2-4 player_stats.txt

This particular example will also print the columns it the range 2 through 4 of the text file named player_stats.txt.

The following example shows how to use each of these methods in practice.

Example: How to Use awk to Print Range of Columns

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

We can use the following syntax with awk to print each column in the range 2 through 4 of the file:

awk -v f=2 -v l=4 'BEGIN{FS=OFS=" "} {for (i=f;i<=l;i++) printf "%s%s", $i, (i<l ? OFS : ORS)}' player_stats.txt

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

awk print range of columns

Notice that this prints columns 2 through 4 of the file.

Feel free to change the values for f and l to print a different range of columns.

Also note that we could use the following syntax with cut to print columns 2 through 4:

cut -d' ' -f2-4 player_stats.txt

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

Notice that this also prints columns 2 through 4 of the file.

Feel free to use whichever method you prefer.

Related Tutorials

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

How to Use awk to Replace newline with Space
How to Use awk to Replace All Occurrences of String in File
How to Use awk to Extract Substring

Leave a Reply