using sed, remove only one character before number match

Viewed 351

I have a text file like so:

text-text-text-7.7.1-text
text-text-text-text-1.2.4-text
text-text-1.2.4-text

I wish to replace character before numbers to space. So the expected output should be

text-text-text 7.7.1-text
text-text-text-text 1.2.4-text
text-text 1.2.4-text

How would I do that using sed?

I have tried using sed -E 's/-/ /g' but it replaces all - with spaces

text text text 7.7.1 text
text text text text 1.2.4 text
text text 1.2.4 text

as well as sed -E 's/-[0-9]/ /g' and output looks like this:

text-text-text .7.1-text
text-text-text-text .2.4-text
text-text .2.4-text

How do I fix this?

2 Answers

Since you want only one application of the rule, don't use the final /g. And to only apply the replacement when there is a number following, you should include that in the matching rule:

sed 's/-\([0-9]\)/ \1/'

Since you don't want the actual digit to be replaced, the above expression captures it in a group \(...\) and reinserts it via the \1 expression.

As you tagged your question awk this is task for gensub. Let data.txt be name of your file, then you do:

awk '// {print gensub(/-([0-9])/, " \\1", 1)}' data.txt

getting output:

text-text-text 7.7.1-text
text-text-text-text 1.2.4-text
text-text 1.2.4-text

This does use capturing group and reference to it in replacement - like @Thomas answer and does replace first occurence. It is worth noting that gensub allow you to easily change any occurence - if you put 2 as 3rd argument it will replace 2nd occurence and so on.

Related