Home > Software engineering >  How to modify values in delimiter text file in unix
How to modify values in delimiter text file in unix

Time:02-11

I have a huge file with delimited value with '~' example

abc~poi~123~jijda~123~abc

Requirement is to replace the values at 3rd occurrence (which is 123 in our case) to be replaced with 111.

I used the below command

awk -F '~' -v OFS='~' '$3 == "123" {$3 = "111"} 1 ' file.txt > Newfile.txt

this works for manually created file but when it the file was created using utf-8 encoding it doesn't work. Can some one help on this. Thanks!

CodePudding user response:

UTF-8 should be no problem.

# SO71048003.awk
BEGIN {
  FS = OFS = "~"
  out = "Newfile.txt"
}

{
  if ($3 == "123")
    $3 = "111"
  print $0 > out
}

Call:

awk -f SO71048003.awk file.txt
=> Newfile.txt with content:
abc~poi~111~jijda~123~abc

CodePudding user response:

Your awk code with some changes:

awk -F'~' -v OFS='~' '{$3=111} 1' file
abc~poi~111~jijda~123~abc
  • we assign to $3 the 111 value.
  • Related