How to Use awk to Replace All Occurrences of String in File


You can use the gsub command in awk to replace all occurrences of a particular string with another string in a file:

awk '{gsub(/Guard/,"Gd"); print}' player_info.txt

This particular example replaces all occurrences of the string “Guard” with “Gd” in each line of the file named player_info.txt.

If you’d like to save these changes to a new file, you can use the > command as follows:

awk '{gsub(/Guard/,"Gd"); print}' player_info.txt > player_info_new.txt

This saves the changes to a new file named player_info_new.txt.

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

Example: How to Use awk to Replace All Occurrences of String in File

Suppose that we have a file named named player_info.txt that contains the positions of basketball players on various teams.

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

Suppose that we would like to replace each occurrence of “Guard” with “Gd” in each line.

We can use the following syntax to do so:

awk '{gsub(/Guard/,"Gd"); print}' player_info.txt

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

awk replace all occurrences of string in file

Notice that all occurrences of “Guard” have been replaced with “Gd” in each line.

If you would like to save these changes to a new file, then you can use the following syntax:

awk '{gsub(/Guard/,"Gd"); print}' player_info.txt > player_info_new.txt

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

awk replace all occurrences in file and save results to new file

Notice that when we use the cat command to view the contents of this new file we can see that it contains the same values from the original file with all occurrences of “Guard” replaced with “Gd” instead.

Related Tutorials

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

Bash: How to Replace Patterns Using Regex
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply