1

I need to insert a new line, or delimiter, in a text file after a "numeric" string consisting of 10 numbers, then a "-", then either 1 to 4 numbers...

Example:

blahblahrandomtext,1234567890-1234blahblah

Should be:

blahblahrandomtext,1234567890-1234, blahblah

Or:

blahblahrandomtext,1234567890-1234

blahblah

Note that the first set of numbers will always be 10 characters, the numbers after the - will either 1,2,3 or 4 characters, e.g.

1234567890-1
1234567890-12
1234567890-123
1234567890-1234

I've used sed a lot for similar tasks, but can't find a way to work with the last set of numbers which vary from 1 to 4 characters.

0

If you know how to do it with a fixed number of digits, you should know how to do it with a maximum and minimum of repeated chars: Inside the \{\} place the minimum and maximum separated by a comma like this:

sed 's/[0-9]\{10\}-[0-9]\{1,4\}/&,\n/'

for GNU sed; for other versions, use a backslash followed by a literal newline instead of \n

  • Worked perfectly, it was the, maximum and the minimum I was having trouble with... Marked as best answer.. – Kneel B Nov 15 '17 at 22:22
3

sed solution (to insert delimiter ,):

sed -E 's/(^|[^0-9])[0-9]{10}-[0-9]{1,4}/\1&, /' file
  • -E - apply extended regular expressions
  • (^|[^0-9]) matches either the beginning of a line or a non-digit. This ensures that no numbers with more than 10 digits match
  • & - points to the whole matched string

The output:

blahblahrandomtext,1234567890-1234, blahblah
  • Works for this example, but will fail for foo1234567890-42bar. Perhaps better use (^|[^0-9]) instead of \< – Philippos Nov 16 '17 at 6:54
  • @Philippos, I thought that that "numeric" string should be somehow isolated, but, It seems not. Updated – RomanPerekhrest Nov 16 '17 at 7:30
  • No, don't do that. That's the main improvement you made over my answer. As in most questions, we don't really know the whole spectrum of possible input data. My answer (and your edited version) will also accept eleven digits before the dash. Your \< takes care of that, but has other limitations. [^0-9] before the match would limit to 10 digits, but fail on the beginning of the line. So (^|[^0-9]) should cover everything: Only match exactly 10 digits before the dash, no matter whether they appear on the beginning of the line, after letters or other characters. – Philippos Nov 16 '17 at 7:41
  • @Philippos, updated, just for the case if someone(except the OP) would need a proper approach – RomanPerekhrest Nov 16 '17 at 8:02

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.