sed regexp mystery 
Author Message
 sed regexp mystery

Ok, it's sed not perl, but it's primarily a regexp question that I've
encountered (and failed to understand) before. . .

#
# When trying to convert a variable number
# of spaces separating fields, to fields
# separated by single commas, if your "input"
# file looks like the following lines. . .
#
#alpha bravo  charlie   delta    echo    fox
#alpha bravo  charlie   delta    echo    fox
#alpha bravo  charlie   delta    echo    fox
#
# and your're trying to convert it to the following. . .
#
#alpha,bravo,charlie,delta,echo,fox
#alpha,bravo,charlie,delta,echo,fox
#alpha,bravo,charlie,delta,echo,fox
#
# Why don't any of the next 5 lines work?
cat input | sed -e "s/ +/,/g"
cat input | sed -e "s/ */,/g"
cat input | sed -e "s/ {1,10}/,/g"
cat input | sed -e "s/[ ]*/,/g"
cat input | sed -e "s/[ ]+/,/g"
#
# Because the above 5 lines all look like
# valid methods of substituting one comma
# for one or more spaces.
#
# And yet, the next line DOES work.
cat input | sed -e "s/[ ] */,/g"
#

I've also tried the g/before/s//after/g type lines with even less success.

Thoughts?

jkh



Sat, 24 Dec 2005 11:55:46 GMT  
 sed regexp mystery
Hi John.

The reasons these don't work are:

Quote:
> cat input | sed -e "s/ +/,/g"

sed doesn't understand the '+' symbol.

Quote:
> cat input | sed -e "s/ */,/g"

You need to watch at least one space.  This will match at least zero spaces.

Quote:
> cat input | sed -e "s/ {1,10}/,/g"

sed doesn't understand those ranges either.

Quote:
> cat input | sed -e "s/[ ]*/,/g"

Again, this'll match zero spaces which is not what you want.

Quote:
> cat input | sed -e "s/[ ]+/,/g"

sed doesn't understand the '+'.

Quote:
> # And yet, the next line DOES work.
> cat input | sed -e "s/[ ] */,/g"

   cat input | sed -e 's/  */,/g'

will work too.  No need for the square brackets.

HTH

--
Cameron McCormack

   // http://www.csse.monash.edu.au/~clm/
   // icq 26955922



Sat, 24 Dec 2005 12:02:42 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. s/// mystery: regexp challenge

2. Regexp global match mystery?

3. HELP regexp sed?perl?

4. regexp question, joining EOL (awk,sed,etc...)

5. ex-ish or sed-ish regexp manipulation

6. Sed in Perl Script Versus Sed in Unix

7. Perl5: Sym table mystery - help!

8. Mystery bug in perl 4.0 p36 on DEC Alpha OSF/1 v2.1

9. perl5 vs perl4 execution time mystery (to me) -- LONG

10. Mystery of the Perl file choppers

11. Weird scoping mystery.

12. Hash mystery entry

 

 
Powered by phpBB® Forum Software