This sounds like a really banal question, and it's bugging me dearly.

I have a text file, generated by python, that contains a list of host names and ip addresses in the following format:

host46.provider.com =

However, because the file was generated asynchronously, there's a few strange errors in the output. I'm getting lines that look like this:

us9831.provider.com = =

The problem is that it hasn't inserted a newline between the two instances. I've ascertained that (fortunately) the naming convention of the nodes doesn't allow for a number to come before a letter, unless it's before a dot (.)

So what I neeed to happen is:

  • find an instance where a number comes before a dot
  • add a newline between the two

I can't figure out how I'll get sed to maintain the regex match, and copy that over to the next regex.

I've tried this:

cat eg | sed '/[0-9][a-z]/s/[0-9][a-z]/[0-9]\n[a-z]/'

and I have tried this:

cat eg | sed "s/[0-9][a-z]/\n/"

Is sed the right tool? Should I be using awk?

Any suggestions would be warmly welcomed.

  • 1
    The unless it's before a dot (.) part of the statement doesn't allow for a number to come before a letter, unless it's before a dot (.) is confusing. Why isn't doesn't allow for a number to come before a letter enough? What does a number before a letter that's also a dot (or whatever that means) look like? – Ed Morton Aug 21 '20 at 12:56

I'm not sure what the unless it's before a dot (.) part of your requirements means but if your requirement is really just that a number can't be immediately before a letter then if your sed supports \n to produce a newline in the replacement text:

$ sed 's/\([0-9]\)\([[:alpha:]]\)/\1\n\2/' file
us9831.provider.com =
us9832.provider.com =

Otherwise with any sed:

$ sed 's/\([0-9]\)\([[:alpha:]]\)/\1\
\2/' file
us9831.provider.com =
us9832.provider.com =
  • 1
    Perfect! Thank you :) – Lewis Farnworth Aug 21 '20 at 12:57
  • 1
    @LewisFarnworth if you found the answer useful, please consider accepting it so that others facing a similar issue may find it more easily. That way, you don't have to repeat the solution in an acknowledgement statement posted as answer (which would be considered incorrect posting on this site, btw). – AdminBee Aug 21 '20 at 12:59
  • @LewisFarnworth you're welcome, please see stackoverflow.com/help/someone-answers for what to do next. – Ed Morton Aug 21 '20 at 18:41

echo "us9831.provider.com = ="| sed "s/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/&\n/g"


us9831.provider.com =
us9832.provider.com =

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.