14

I have a file like this:

2018.01.02;1.5;comment 1
2018.01.04;2.75;comment 2
2018.01.07;5.25;comment 4
2018.01.09;1.25;comment 7

I want to replace all dots . in the second column with a comma , as I would with sed 's/\./\,/g' file how can I use sed or preferably awk to only apply this for the second column, so my output would look like this:

2018.01.02;1,5;comment 1
2018.01.04;2,75;comment 2
2018.01.07;5,25;comment 4
2018.01.09;1,25;comment 7
24
$ awk 'BEGIN{FS=OFS=";"} {gsub(/\./, ",", $2)} 1' ip.txt
2018.01.02;1,5;comment 1
2018.01.04;2,75;comment 2
2018.01.07;5,25;comment 4
2018.01.09;1,25;comment 7
  • BEGIN{} this block of code will be executed before processing any input line
  • FS=OFS=";" set input and output field separator as ;
  • gsub(/\./, ",", $2) for each input line, replace all the . in 2nd field with ,
  • 1 is an awk idiom to print contents of $0 (which contains the input record)
| improve this answer | |
  • 1
    awesome, much THX! – nath Jan 4 '19 at 15:19
9
sed 's/\./,/3' file

replace the third occurence of the dot

| improve this answer | |
  • 2
    Another Useles Use of cat... Why not just sed 's/\./,/3' file? (Also, the comma does not need to be escaped.) – twalberg Jan 4 '19 at 15:42
  • I took into account the observations – Emilio Galarraga Jan 4 '19 at 15:54
  • cat would not necessarily be useless here. It would allow the operation to use 2 cores. – ron rothman Jan 5 '19 at 1:40
  • @ronrothman what would the purpose of the core running cat be, other than using up resources? Maybe to provide a little buffer, but then this intention should be better expressed by a tool like buffer than by cat. – Roland Illig Dec 15 '19 at 12:03
  • To decouple the (blocking) disk reads from the string replacement. Yes, I suppose you can think of it as buffering. – ron rothman Dec 15 '19 at 14:30
4

Done by below method using awk

Command: awk -F ";" '{gsub(/\./,",",$2);print $1";"$2";"$3}' filename

output

2018.01.02;1,5;comment 1
2018.01.04;2,75;comment 2
2018.01.07;5,25;comment 4
2018.01.09;1,25;comment 7
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.