J.Carter J.Carter - 1 month ago 8
Perl Question

Regex for replacing space with comma-space, except at end of line

I am trying to covert input file content of this:

NP_418770.2: 257-296 344-415 503-543 556-592 642-707
YP_026226.4: 741-779 811-890 896-979 1043-1077


to this:

NP_418770.2: 257-296, 344-415, 503-543, 556-592, 642-707
YP_026226.4: 741-779, 811-890, 896-979, 1043-1077


i.e., replace a space with comma and space (excluding newline)

For that, I have tried:

perl -pi.bak -e "s/[^\S\n]+/, /g" input.txt


but it gives:

NP_418770.2:, 257-296, 344-415, 503-543, 556-592, 642-707
YP_026226.4:, 741-779, 811-890, 896-979, 1043-1077


how can I stop the additional comma which appear after ":" (I want ":" and a single space) without writing another regex?

Thanks

Answer

Try using regex negative lookbehind. It is basically look if character before the space is colon (:) then it don't match the space.

s/(?<!:)[^\S\n]+/, /g
Comments