Skip to main content
2 of 2
added 34 characters in body
terdon
  • 252.2k
  • 69
  • 480
  • 718

You haven't really explained how we can know which commas to keep and which to change. Based on the single example line you have given us, it might be enough to just replace all , that don't come after a space with a |:

$ sed -E 's/,(\S)/\|\1/g' file
Name|Age|Country|ID|Address|Category|DOB
John Doe|19|England|3653|Manchester, England|Main Worker|20-05-1995

Or, if you really don't want to change the header:

$ sed -E '2,${s/,(\S)/\|\1/g}' file
Name,Age,Country,ID,Address,Category,DOB
John Doe|19|England|3653|Manchester, England|Main Worker|20-05-1995

Alternatively, if we cannot rely on the space and instead need replace all commas except the 5th on lines that to something like this: "if this line has more than 7 fields, then consider the 5th , in the line as part of the 4th field and not as a delimiter". If so, this should work for you:

$ $ perl -F, -lane 'if($#F>6){$F[4].=",$F[5]"; splice(@F,5,1)} print join("|",@F)' file
Name|Age|Country|ID|Address|Category|DOB
John Doe|19|England|3653|Manchester, England|Main Worker|20-05-1995

Or, again, if you really don't want to change the header, use:


$ perl -F, -lane 'if($#F>6){$F[4].=",$F[5]"; splice(@F,5,1)} $.==1 ? print : print join("|",@F)' file
Name,Age,Country,ID,Address,Category,DOB
John Doe|19|England|3653|Manchester, England|Main Worker|20-05-1995
terdon
  • 252.2k
  • 69
  • 480
  • 718