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

  • -FS=”;” set input field separator as ;
  • -OFS=";" set output field separator as ;
  • gsub("-", ",", $1) for each input line, replace all the – in 1nd field with .
  • print output replace content

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
  • BEGIN{} this block of code will be executed before processing any input line
  • FS=OFS=";" set input and output field separator as ;

Add a Comment

Your email address will not be published.