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"

3 Answers 3

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'
8
  • Do we need to escape the double quotes? Commented Jan 22, 2015 at 20:47
  • 1
    @muru Yes, you are right, it is overcautious. Made edition. Commented 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". Commented Jan 22, 2015 at 21:47
  • @Costas where is your edit? Commented Jan 24, 2015 at 2:15
  • @AvinashRaj In my post. Commented Jan 24, 2015 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"
0

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"
1
  • While not sed, this is helpful, as stated, for cases where multiple commas shows in the quotes. Commented Aug 22, 2019 at 15:28

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.