I have text file including text format like this.


How do i replace comma inside words only within double quote by pipe(|) operator using sed. I need output like this :

012345,"[ThinkPadT2/3Gband | Mac]",Lenovo,"iPhone3G|A1241"

3 Answers 3


This is standard procedure to make sed non-greedy and back-reference tip for substring(s) in brackets ()

sed 's/\(\"[^",]\{1,\}\),\([^",]\{1,\}\"\)/\1 | \2/g'

Or for GNU sed

sed -r 's/("[^",]+),([^",]+")/\1 | \2/g'
  • Do we need to escape the double quotes?
    – muru
    Jan 22, 2015 at 20:47
  • 1
    @muru Yes, you are right, it is overcautious. Made edition.
    – Costas
    Jan 22, 2015 at 21:10
  • 1
    This assumes that each quoted string contains exactly one comma. It fails on 012345,"[ThinkPadT2/3Gband-Mac]",Lenovo,"iPhone3G,A1241" and 012345,"[ThinkPadT2,3Gband,Mac]",Lenovo,"iPhone3G,A1241". Jan 22, 2015 at 21:47
  • @Costas where is your edit? Jan 24, 2015 at 2:15
  • @AvinashRaj In my post.
    – Costas
    Jan 24, 2015 at 12:01

You could try something like this:

$ cat filename

$ cat filename | sed -E 's:([A-Z,a-z]),([A-Z,a-z]):\1|\2:g'

Sed is not the right tool for this. I think it may require some advanced features to achieve like the above. Here is the perl on-liner which replaces any number of double commas present within double quotes with <space>|<space> .

$ echo '012345,"[ThinkPadT2/3Gband,Mac,Apple]",Lenovo,"iPhone3G,A1241"' | perl -pe 's/,(?!(?:"[^"]*"|[^"])*$)/ | /g'
012345,"[ThinkPadT2/3Gband | Mac | Apple]",Lenovo,"iPhone3G | A1241"
  • While not sed, this is helpful, as stated, for cases where multiple commas shows in the quotes.
    – Mike
    Aug 22, 2019 at 15:28

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.