Replace all occurrence of character except first one

This can be done with this,

$ sed -e 's/,/;/g' -e 's/;/,/1' infile
test1,test2;test3
test4,test5
test6,test7;test8;test9;test10
test11,test12;test13;test14

Explanation

  • s/,/;/g replaces all occurrence of , with ;

  • s/;/,/1 replaces the first occurrence of ; with ,


If you have GNU sed, you can also try this simple and handy,

sed 's/,/;/2g' infile

If the input might already have semicolons in it, we have to be careful:

$ sed 's/,/\n/g; s/\n/,/; s/\n/;/g' input
test1,test2;test3
test4,test5
test6,test7;test8;test9;test10
test11,test12;test13;test14

Since sed reads the input line-by-line, there will be no newline characters in normal input. So, we can replace all the commas with newlines and we know that there will be no confusion. Next we restore the first newline back to a comma. Lastly, we replace all remaining newlines with a semicolon.

In more detail:

  • s/,/\n/g replaces all commas with newlines.

  • s/\n/,/ replaces the first newline with a comma.

  • s/\n/;/g replaces all remaining newlines with semicolons.


Using awk:

awk '{gsub(",", ";"); sub(";", ","); print}' file.txt
  • gsub(",", ";") replaces all , with ;

  • sub(";", ",") replaces the first ; with ,

Example:

% cat file.txt
test1,test2,test3
test4,test5
test6,test7,test8,test9,test10
test11,test12,test13,test14

% awk '{gsub(",", ";"); sub(";", ","); print}' file.txt
test1,test2;test3
test4,test5
test6,test7;test8;test9;test10
test11,test12;test13;test14