0

I have text file including text format like this.

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

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"
2

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 '15 at 20:47
  • 1
    @muru Yes, you are right, it is overcautious. Made edition. – Costas Jan 22 '15 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". – Scott Jan 22 '15 at 21:47
  • @Costas where is your edit? – Avinash Raj Jan 24 '15 at 2:15
  • @AvinashRaj In my post. – Costas Jan 24 '15 at 12:01
0

You could try something like this:

$ cat filename
012345,"[ThinkPadT2/3Gband,Mac]",Lenovo,"iPhone3G,A1241"

$ cat filename | sed -E 's:([A-Z,a-z]),([A-Z,a-z]):\1|\2:g'
012345,"[ThinkPadT2/3Gband|Mac]",Lenovo,"iPhone3G|A1241"
-1

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"

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.