Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace with SED multiple occurences at the same line

Tags:

linux

bash

sed

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/
like image 388
yorgo Avatar asked Oct 14 '25 04:10

yorgo


2 Answers

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."

like image 110
Beta Avatar answered Oct 16 '25 16:10

Beta


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
like image 24
Inian Avatar answered Oct 16 '25 17:10

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!