tags:

views:

42

answers:

3

I try to replace the char # with a newline \n:

sed -e "s/#/\n/g" > file.txt

this works fine.

Now there is problem with the char #, when is escaped with -:

eg.: 123#456-#789#777 should be:
123
456#789
777

The escaped char - itself can also be escaped: eg.: 123#456-#789--012#777 should be:
123
456#789-012
777

How can i do this with sed ?

+1  A: 
$ echo "123#456-#789#777" | sed 's/\([^-]\)#/\1\n/g;s/-\(.\)/\1/g'
123
456#789
777

$ echo "123#456-#789--012#777" | sed 's/\([^-]\)#/\1\n/g;s/-\(.\)/\1/g'
123
456#789-012
777

$ echo "#123#456-#789#777" | sed 's/\(^\|[^-]\)#/\1\n/g;s/-\(.\)/\1/g'

123
456#789
777

$ echo "#1###2-#3--4#5#" | sed "s/\([^-]\)##/\1#\n/g;s/\(^\|[^-]\)#/\1\n/g;s/-\(.\)/\1/g" 

1


2#3-4
5

$

First part is to preserve -<any chars> and convert # (without the preceding -) to newline, second part is to convert -<any chars> to only <any chars> (If you don't need such wildcard, I think you know how to modify for only - and #.)

livibetter
what about echo "#123#456-#789#777" | sed 's/\([^-]\)#/\1\n/g;s/-\(.\)/\1/g'
newGuest
@newGuest, are you expecting a newline before '123'? Then sed 's/\(^\|[^-]\)#/\1\n/g;s/-\(.\)/\1/g' is what you want.
livibetter
the newline CAN be there - but this dont work: echo "1##2#3" | sed "s/\(^\|[^-]\)#/\1\n/g;s/-\(.\)/\1/g"
newGuest
@newGuest, could you edit your question for the expected result for the case?
livibetter
"#1##2#3" should be: <LF>1<LF><LF>2<LF>3 - so every 'normal' # should be a newline (<LF>)
newGuest
GREAT - THANK YOU
newGuest
A: 

sed -e "s/([^-])#/\1\n/g;s/--/-/g;s/-#/#/g"

This only escapes -- and -# though.

Holstebroe
A: 
$ echo "123#456-#789--012#777" | awk -F"#" '{print $1;for(i=2;i<NF-1;i++){printf "%s#",$i};print $(NF-1);print $NF}'
123
456-#789--012
777
$ echo "123#456-#789#777" | awk -F"#" '{print $1;for(i=2;i<NF-1;i++){printf "%s#",$i};print $(NF-1);print $NF}'
123
456-#789
777
ghostdog74