如何剪切bash数组中的最后3个元素并将它们添加到数组中

时间:2014-07-18 15:37:05

标签: arrays bash unix sed ifs

好吧我目前正在编写一个脚本,该脚本将采用一个带有"〜"的分隔符的文件。拆分它。然而,它们是数组中的一个项[5]元素需要占用该元素的最后3个单词,将它们剪切掉并将它们分配给数组中的不同值,然后重新调整元素[5]以删除这些项目。我尝试了sed,cut和其他命令,但是我迷失了。我正在使用bash这个脚本,下面是我的问题的简短形式。

#!#!/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

当前打印:

[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 

通缉打印:

[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 

2 个答案:

答案 0 :(得分:2)

你可以这样做:

#!#!/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[@]}"

输出:

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

答案 1 :(得分:1)

将您的STR调整为NEW_STR并将其与IFS =〜(小2行更改)

一起使用
$ cat 1.sh
#!/bin/bash
STR="FAILED~LOSS~Positive~MULTICOUNT~1~LOSS SUMMARY - Log: One vs TWO DAD MAR  DE~5~489646.22~469646.22~5"

NEW_STR="$(echo $STR | sed "s/TWO DAD MAR DE/TWO~DAD~MAR~DE/")"

IFS="~" read -ra STR_ARRAY <<< "$NEW_STR"
for x in "${STR_ARRAY[@]}"
    do
            echo "> [$x]"
done

输出:

$ ./1.sh
> [FAILED]
> [LOSS]
> [Positive]
> [MULTICOUNT]
> [1]
> [LOSS SUMMARY - Log: One vs TWO]
> [DAD]
> [MAR]
> [DE]
> [5]
> [489646.22]
> [469646.22]
> [5]