How to Use Multiple Delimiters in awk (With Example)


Often you may want to use awk to read content from a file that contains multiple delimiters.

You can use the following basic syntax to do so:

awk -F'[: ]' '{OFS=" ";print $1,$3,$4}' athlete_stats.txt

This particular example extracts columns 1, 3 and 4 from the CSV file named athlete_stats.txt.

Here is what the various awk commands do:

  • -F specifies the input delimiters
  • ‘[: ]’ specifies that a colon and a space should both be recognized as delimiters
  • OFS=” “ specifies that the printed output delimiter should be a space
  • $1,$4 specifies that columns 1 and 4 should be extracted from the file

Note that we used two delimiters in this particular example but you can include as many delimiters as you would like within the brackets.

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

Example: How to Use Multiple Delimiters in awk

Suppose that we have a file named athlete_stats.txt that contains information about various basketball players.

We can use the cat command to view the contents of this file:

awk multiple delimiters

Notice that the fields in the file are separated by either colons or spaces.

Suppose that we would like to extract columns 13 and 4 from the file.

We can use the following syntax to do so:

awk -F'[: ]' '{OFS=" ";print $1,$3,$4}' athlete_stats.txt

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

awk multiple delimiters

Notice that this returns columns 1 (“team” column), 3 (“assists” column) and 4 (“rebounds” column) from the file.

Feel free to change $1, $3 and $4 to whatever numbers you would like depending on which columns you would like to extract from your own file.

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 Specific Columns from File
How to Use awk to Extract Substring

Leave a Reply