Home > Back-end >  Seperate a range into single line adding the values in between
Seperate a range into single line adding the values in between

Time:11-09

I have a text list with values in a range as follows:

TSNN-00500--00503 TSNN-00510--00515 

But I need to separate them into single lines in a text file and add the values in between.

Can this be done with a script easily?

Want the result in a new text file as follow

TSNN-00500
TSNN-00501
TSNN-00502
TSNN-00503
TSNN-00510
TSNN-00511
TSNN-00512
TSNN-00513
TSNN-00514
TSNN-00515

CodePudding user response:

easy way is subjective.

Getting a sequence from a range can be performed with seq:

$ seq -f.0f 00500 00503
00500
00501
00502
00503

Getting the range from the string you provide can be performed with bash find-and-replace:

$ text='TSNN-00500--00503'
$ echo ${text//[^0-9]/ }
00500 00503

Prepending a string to a line can be performed with sed:

$ echo 00502 | sed 's/^/TSNN-/'
TSNN-00502

Wrapping everything in a loop gives:

$ for i in TSNN-00500--00503 TSNN-00510--00515 ; do seq -f.0f ${i//[^0-9]/ } | sed 's/^/TSNN-/' ; done

CodePudding user response:

You can try this awk:

echo 'TEST-00000 TSNN-00500--00503 TSNN-00510--00515' |
awk '
    {
        for (i = 1; i <= NF; i  ) {
            n = split($i,arr,"-")
            if ( n == 4 ) {
                fmt = "%0" length(arr[2]) "d"
                for (j = arr[2]; j <= arr[4]; j  )
                    print arr[1] "-" sprintf(fmt, j)
            } else
                print $i
        }
    }
'
TEST-00000
TSNN-00500
TSNN-00501
TSNN-00502
TSNN-00503
TSNN-00510
TSNN-00511
TSNN-00512
TSNN-00513
TSNN-00514
TSNN-00515
  • Related