Berkeley CSUA MOTD:Entry 47500
Berkeley CSUA MOTD
 
WIKI | FAQ | Tech FAQ
http://csua.com/feed/
2025/07/08 [General] UID:1000 Activity:popular
7/8     

2007/8/1 [Computer/SW/Unix, Computer/SW/Languages/Perl] UID:47500 Activity:high
8/1     perl/sed/awk/etc question:
        Is there a good way to change every other delimiter or string
        match?  For example change a colon delimited list to a :+, one...
         Apple:12:Pear:2:Orange:9:Plum:7:Banana:22:Mango:2 to
         Apple:12,Pear:2,Orange:9,Plum:7,Banana:22,Mango:2
        (And I dont mean a trick that relies on some fields being
        alpha and some numeric or only a known number of fields).
        \_ How 'bout the straightforward approach
           s/([^:]+:[^:]+):/$1,/g
           \_ That didn't work?!  Am I doing something wrong?
              echo Apple:12:Pear:2:Orange:9 |sed -e 's/([^:]+:[^:]+):/$1,/g'
              Apple:12:Pear:2:Orange:9
              \_ use perl, sed will kill you with quoting.
                 \_ Thanks! perl -pe ... does it!
              \_ One more question, why is there a differene between : and |?
                 I now need to use |.
 echo "Prog 1:61.3:Ch 2:91.0:Num3:83.4" |perl -pe 's/([^:]+:[^:]+):/$1,/g'
Prog 1:61.3,Ch 2:91.0,Num3:83.4

 echo "Prog 1|61.3|Ch 2|91.0|Num3|83.4" |perl -pe 's/([^|]+|[^|]+)|/$1,/g'
Prog 1,,|61.3,,|Ch 2,,|91.0,,|Num3,,|83.4
                 First one works. Second does not.
                 \_ man perlre, search for |