Linux sed and awk Cheat Sheet/Replace text in awk

Use `sub` and `gsub` for replacements.

Section: awk Scripting Patterns

Replace text in awk

bash
bash
awk '{gsub(/foo/, "bar"); print}' file.txt
Explanation

`sub` replaces one match, while `gsub` replaces all matches in the current record.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing awk Scripting Patterns
Use BEGIN and END blocks
Print headers and footers around processed output.
OpenIn sheetbashsame section
Process command output
Filter output from another command using awk.
OpenIn sheetbashsame section
Match with regex in awk
Print only lines that match a regex.
OpenIn sheetbashsame section
Skip a header row
Ignore the first line of a delimited file.
OpenIn sheetbashsame section
Replace first occurrence per line
Substitute one match in each line.
OpenIn sheetbash1 tag match
Print selected columns
Show the first and third whitespace-delimited fields.
OpenIn sheetbash1 tag match