Your data consists of six ;
-delimited fields, and you'd like to replace the dots in fields 2 through to 5 (not 1 or 6) with commas.
This is easiest done with awk
:
awk -F ';' 'BEGIN { OFS=FS } { for (i=2; i<=5; ++i) gsub("\\.", ",", $i); print }' file
With the example data given, this produces
2019-03-17T11:32:28.143343Z;1234,5678;901,234;567,89012;3456,78;192.168.0.1
The code simply iterates of the ;
-delimited fields of each input line and calls gsub()
to do a global search and replace (as you would do with s/\./,/g
or y/./,/
in sed
) on the individual fields that the loop iterates over.
The modified line is then printed.
The -F
option sets the input field separator to a semicolon, and we use the BEGIN
block to also set the output field separator to the same value (you would otherwise get space-separated fields).
Using sed
, you might do something like
sed 's/\./,/2; s/\./,/2; s/\./,/2; s/\./,/2' file
I.e., replace the 2nd dot four times (which one is the 2nd dot will change with each substitution, since you substitute them). This does however assume that the number of values within each field remains static.
To work around this in case you at some point have more than two dot-delimited things in a field, you can do
sed 'h; s/^[^;]*;//; s/;[^;]*$//; y/./,/; G;H;x; s/;[^\n]*\n/;/; s/\n.*;/;/' file
In short, these commands do
- Copy the original line to the hold space.
- Remove the first and last fields in the pattern space.
- Change all dots to commas in the pattern space (that's the
y
command). All dots that should change into commas have now been changed. Now we must reassemble the line from the middle bit in the pattern space and the original data in the hold space.
Make (with G;H;x
) the pattern space contain
- The original string, followed by a newline,
- The modified middle bit, followed by a newline
- The original string again.
So now the pattern space contains three lines. Remove everything but the first field on the first line, and the newline, and replace that removed bit with a ;
.
Do a similar thing with the last line, i.e. remove the (now lone) newline and everything up to the last ;
, and replace with a ;
.
Done.
Or you could just use the awk
code.