How to Use awk to Extract Substring (With Examples)


Often you may want to use awk to extract a specific substring from a string.

You can use the methods to do so:

Method 1: Extract Substring Before Pattern

awk '{sub(/:.*/, ""); print}' team_list.txt

This particular example extracts the substring before the colon ( : ) in each line of the file named team_list.txt.

Note that we use the sub command to substitute everything starting from the colon including all characters after that with nothing, which leaves only the substring that occurs before the colon.

Method 2: Extract Substring After Pattern

awk '{sub(/.*: /, ""); print}' team_list.txt

This particular example extracts the substring after the colon and the space in each line of the file named team_list.txt.

Note that we use the sub command to substitute everything up to and including the colon with nothing, which leaves only the substring that occurs after the colon.

The following examples show how to use each method in practice with the following text file named team_list.txt:

Example 1: Use awk to Extract Substring Before Pattern

We can use the following syntax to extract the substring before the colon in each line of the file:

awk '{sub(/:.*/, ""); print}' team_list.txt

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

Notice that this returns the substring before the colon in each line, which is simply the substring Team for each line.

Example 2: Use awk to Extract Substring After Pattern

We can use the following syntax to extract the substring after the colon and the space in each line of the file:

awk '{sub(/.*: /, ""); print}' team_list.txt

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

awk extract substring after pattern

Notice that this returns the substring after the colon and the space in each line.

Related Tutorials

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

How to Use awk to Replace newline with Space
How to Use awk to Replace All Occurrences of String in File
How to Use Bash to Filter for Lines in File that Start with String

Leave a Reply