How to Use awk to Print Double Quotes in Output


Often you may want to use awk to print double quotes around each field in the output of a file.

You can use the following syntax to do so:

awk '{for (i=1;i<=NF;i++) $i="\""$i"\""}1' player_stats.txt

This particular example prints all fields from the text file named player_stats.txt with double quotes around the values in each field.

Note that this method uses a for loop to print all fields with double quotes by using \”” to escape double quotes on each side of the field.

Note that we use the syntax NF in the for loop to represent “number of fields”, which extracts the last field in a particular file. This allows us to loop through each field in the file.

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

Example: How to Use awk to Print Double Quotes in Output

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 each field from this file in double quotes.

We can use the following syntax to do so:

awk '{for (i=1;i<=NF;i++) $i="\""$i"\""}1' player_stats.txt

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

awk print double quotes

Notice that this prints each field from the file with double quotes.

Feel free to change the values in the for loop to print a different range of fields from the file instead.

Related Tutorials

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

How to Use awk to Print All Fields Except First Field
How to Use awk to Print Last Column of File
How to Use awk to Extract Substring

Leave a Reply