I want to add a "/" before each number using sed:

    echo 1 2 3 4 5 6 7  | sed 's/[ ^]*/&\//g'

    /1 /2 /3 /4 /5 /6 /7/

When I use this syntax, why do I get the "/" after 7? How can I fix my sed syntax in order to get this:

    /1 /2 /3 /4 /5 /6 /7
link|improve this question

40% accept rate
feedback

2 Answers

up vote 2 down vote accepted

Give this a try:

echo '1 2 3 4 5 6 7' | sed 's|\w\+|/&|g'
link|improve this answer
feedback

to fix it: prepend the slash before the beginning of a number (i use the :to separate pattern and replacement instead of /, no need to escape the slash then)

 % echo 1 2 3 4 5 6 7 | sed 's:\([1-9]\+\):/\1:g'

the problem of your command is, that you use the *to match either space or a carret ^. and not just one of them but any number of them, including 0. that matches at the end of the line (after the 7) as well (and luckily for you also at the beginning).

to make this work with either word (aka nonspace) use this:

 % echo ha hu 1 2 ho | sed 's:[^ ]\+:/&:g'
link|improve this answer
I get /1 /2 /3 /4 /5 /6 /71 (why 1 number after 7?) – yael Jan 23 '11 at 14:00
you get 1 because i added a 1 to the last 7 to give you a pattern that works on any integer, not only single digits. – akira Jan 23 '11 at 14:03
but I dont want 1 after 7 – yael Jan 23 '11 at 14:08
any way this is numbers example could be words and your sed fit for numbers – yael Jan 23 '11 at 14:10
then a) be more specific in your question and b) replace "71" with "7" by pure imagination. – akira Jan 23 '11 at 14:12
show 3 more comments
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.