Sed: replace spaces with tab, only if word starts with digit

I want to use sed to replace one or more consecutive spaces with a single tab, where the new word starts with a digit. Currently using bash with the following:
sed -i 's/[[:blank:]]\+/\t/g' file.txt
The file could look something like this and there are only spaces:

Foo      100
Bar      1000
Foo Baz  33
Lorem ipsum 55

The last two lines are also space delimited, but there I want have Foo Baz and Lorem ipsum not be tab delimited, because Baz nor ipsum start with a digit. How do I change the code to make this happen?

Welcome @technossomy.

Using GNU sed like in your example, you can try:

sed -i 's/[[:blank:]]\+\([0-9]\)/\t\1/' file.txt

or using GNU sed's extended regular expression, try:

sed -ri 's/[[:blank:]]+([0-9])/\t\1/' file.txt
1 Like

Thank you, I didn't realise the function of \1 until now.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.