4

I want to replace all slashes "/" between alphanumeric with backslash+slash "\/" apart from the last one on each string, e.g.

nocareNocare abc\/def/ghi/mno\/pq/r   abc\/def\/ghi/mno\/pq/r

should become:

nocareNocare abc\/def\/ghi\/mno\/pq/r   abc\/def\/ghi\/mno\/pq/r

I use:

sed 's/\(.*\)\([[:alnum:]]\)\/\([[:alnum:]]\)\(\S*\)\(\\\|\/\)/\1\2\\\/\3\4\//g'

Short explanation: match

any string + alnum + / + any non-white + / or \

But it only replace one case, so I need to run it 3 times to replace all 3 occurences. Looks like the first time it matches all the way to :

>nocareNocare abc\/def/ghi/mno\/pq/r   abc\/def\/ghi/

instead of

>nocareNocare abc\/def/
0

3 Answers 3

4
sed -e :a -e 's|\([a-z0-9]\)/\([a-z0-9][^ ]*[a-z0-9]/[a-z0-9]\)|\1\\/\2|;ta' filename

Loosely translated, this says "replace a lone slash followed by some other stuff in the string, followed by another lone slash, with backslash-slash and that same stuff (and the second slash). And after making such a replacement, start over again."

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a perl command line solution based on the following regEx's

(?<!\\)

not preceded by a backslash

(?!\w+\s)

not followed by word characters terminating in whitespace

perl -pe 's;(?<!\\)/(?!\w+\s);\\/;g' file
nocareNocare abc\/def\/ghi\/mno\/pq/r   abc\/def\/ghi\/mno\/pq/r

2 Comments

You cracked it! Thanks for your help from the start to the end! I also handles case that there an underscore before the slash, which is great.
@user2405602: Cheers! Happy to help!
1

With GNU sed:

sed -E 's:([^\])/:\1\\/:g;s:\\/([^\]*( |$)):/\1:g' file

Two s command here:

  • s:([^\])/:\1\\/:g replace all / not preceded by a \ with \/
  • s:\\/([^\]*( |$)):/\1:g replace last \/ before space or end of line with /

1 Comment

Thanks, but this is doesn't do it, because the 2nd step you describe also replaces some "\/" that were there in the initial version, and that I do not want.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.