sed, insert whitespace before first number but only if whitespace is not present

Viewed 174

This needs to be via sed sadly and from what I can tell, reverse matches don't work.

I have an incorrect string that I need to insert a space into, this incorrect string can take the format:

>=5.0.0 <= 7.0.0
>5.0.0 <= 7.0.0
=5.0.0 <= 7.0.0

I need to insert a space before the first number and only if there isn't a white space present (we have hundreds of string that are correct so double whitespaces would break them).
The desired output is

>= 5.0.0 <= 7.0.0
> 5.0.0 <= 7.0.0
= 5.0.0 <= 7.0.0

I've tried playing with grouping but haven't quite got it:

echo $testString |sed 's/\(\S\)\w/\1 &/'
>= =5.0.0 < 7.0.0
3 Answers

In case you are ok with awk, could you please try following, written and tested with shown samples.

awk '!/^[>]?[=]? [0-9]/{sub(/[>]?[=]?/,"&"OFS)} 1' Input_file

OR

awk '/^[>]?[=]?[0-9]/{sub(/[>]?[=]?/,"&"OFS)} 1' Input_file

OR with sed using same regex:

sed -E '/^[>]?[=]?[0-9]/s/^[>]?[=]?/& /' Input_file

I also want to suggest another regex.

sed -E 's/([<>=]+)([0-9])/\1 \2/g' file

It depends on what else could be at the start of the line, but this works using POSIX character class notations and covers many more sequences of characters than just the relational operators shown in the sample data:

sed -e 's/\([^[:space:][:digit:]]\{1,\}\)\([[:digit:]]\)/\1 \2/' <<'EOF'
>=5.0.0 <= 7.0.0
>5.0.0 <= 7.0.0
=5.0.0 <= 7.0.0
EOF

Output:

>= 5.0.0 <= 7.0.0
> 5.0.0 <= 7.0.0
= 5.0.0 <= 7.0.0

The regex looks a sequence of one or more 'not space, not digit' characters at the start of a line, followed by a digit, and inserts a space before the digit.

Related