Search code examples
arraysbashunixsedifs

How to cut Last 3 elements in bash array and add them to an array


ALright I currently am writting a script that will take a file with a delimiter of "~" and split it. However their is one item in the array the [5] element that needs to take the last 3 words of that element, cut them out and assign them to different values in the array, and then re adjust the element [5] to remove these items. I have tried sed, cut and other commands, but I am lost however. I am using bash for this script and below is the short form of my problem.

#!#!/bin/bash 
STR="FAILED~LOSS~Positive~MULTICOUNT~1~LOSS SUMMARY - Log: One vs TWO DAD MAR  DE~5~489646.22~469646.22~5" 
IFS="~" read -ra STR_ARRAY <<< "$STR"

for x in "${STR_ARRAY[@]}"
    do
            echo "> [$x]"
    done

Current Print:

[0] = FAILED
[1] = LOSS
[2] = Positive
[3] = MULTICOUNT
[4] = 1
[5] = LOSS SUMMARY - Log: One vs TWO DAD MAR DE
[6] = 5
[7] = 489646.22
[8] = 469646.22
[9] = 5 

Wanted Print:

[0] = FAILED
[1] = LOSS
[2] = Positive
[3] = MULTICOUNT
[4] = 1
[5] = LOSS SUMMARY - Log: One vs TWO 
[6] = DAD 
[7] = MAR 
[8] = DE
[9] = 5
[10] = 489646.22
[11] = 469646.22
[12] = 5 

Solution

  • You can do this:

    #!#!/bin/bash 
    STR="FAILED~LOSS~Positive~MULTICOUNT~1~LOSS SUMMARY - Log: One vs TWO DAD MAR  DE~5~489646.22~469646.22~5" 
    IFS="~" read -ra STR_ARRAY <<< "$STR"
    IFS=" " read -ra T <<< "${STR_ARRAY[5]}"
    STR_ARRAY2=("${STR_ARRAY[@]:0:5}" "${T[*]:0:${#T[@]} - 3}" "${T[@]:(-3)}" "${STR_ARRAY[@]:6}")
    printf '%s\n' "${STR_ARRAY2[@]}"
    

    Output:

    FAILED
    LOSS
    Positive
    MULTICOUNT
    1
    LOSS SUMMARY - Log: One vs TWO
    DAD
    MAR
    DE
    5
    489646.22
    469646.22
    5