Site icon LinuxCommands.site

awk replace statement and examples

Awk replace statement can help us format the input data conveniently.

This article shows you how to use the awk command to search and replace field values.

The awk search and replace function requires the use of awk string manipulation functions: gsub()

gsub syntax:

gsub(regexp, replacement [, target])

Search target for all of the longest, leftmost, nonoverlapping matching substrings it can find and replace them with replacement. The ‘g’ in gsub() stands for “global,” which means replace everywhere.

awk replace example

Test file: t.log

2020-10-19;awk;20.32
2020-10-19;grep;21.32
2020-10-19;ls;10.24
2020-10-19;find;9.10
2020-10-19;rm;20.198

Output result:

2020.10.19;awk;20.32
2020.10.19;grep;21.32
2020.10.19;ls;10.24
2020.10.19;find;9.10
2020.10.19;rm;20.198

Separate the input line with “;” and replace the “-” in the first paragraph with “.”.

Way 1:

➜  ~ awk -F';' -FS';' '{gsub("-",".",$1);print}' t.log
2020.10.19;awk;20.32
2020.10.19;grep;21.32
2020.10.19;ls;10.24
2020.10.19;find;9.10
2020.10.19;rm;20.198

Way 2:

➜  ~ awk 'BEGIN{FS=OFS=";"}{gsub("-",".",$1);print}' t.log
2020.10.19;awk;20.32
2020.10.19;grep;21.32
2020.10.19;ls;10.24
2020.10.19;find;9.10
2020.10.19;rm;20.198

Exit mobile version