1

I have the following array:

declare -a case=("060610" "080813" "101016" "121219" "141422")

I want to generate another array where the elements have whitespaces inserted appropriately as:

"06 06 10" "08 08 13" "10 10 16" "12 12 19" "14 14 22"

I got till handling the elements individually using sed as:

echo '060610' | sed 's/../& /g'

But I am not being able to do it while using the array. The sed confuses the white spaces in between the elements and I am left with the output:

echo "${case[@]}" | sed 's/../& /g'

Gives me:

06 06 10  0 80 81 3  10 10 16  1 21 21 9  14 14 22

Can someone help?

8
  • Show your code that assigns to the new array. Commented Nov 14, 2016 at 21:31
  • For the output I am talking about, I used this: echo "${case[@]}" | sed 's/../& /g' But I am yet to know a lot about using @ for calling an element. And still getting familiar with usage of braces and quotes. Commented Nov 14, 2016 at 21:32
  • Put the code in the question. Commented Nov 14, 2016 at 21:34
  • Where did the previous answer go? Commented Nov 14, 2016 at 21:36
  • he deleted it because it didn't really work. Commented Nov 14, 2016 at 21:37

2 Answers 2

2

You need to loop over the array, not echo it as a whole, because you don't get the grouping when you echo it.

declare -a newcase
for c in "${case[@]}"
do
    newcase+=("$(echo "$c" | sed 's/../& /g')")
done
Sign up to request clarification or add additional context in comments.

6 Comments

To append a new element to the array.
declare -a kpts for c in "${case[@]}"; do kpts+=$(echo "$c" | sed 's/../&/g'); done gives me: 060610080813101016121219141422 Am I doing alright?
You seem to be missing the space after &. How are you printing the array?
Sorry, I made a mistake, you have to wrap the value in () to create a new array element.
I am printing it using echo "${kpts[3]}" But now 06 06 10... resp are the 0th, 1st, 2nd element of the array. I wanted 06 06 10 as the 0th element rather. Anyway I will try to use this and see what happens.
|
2

You can use printf '%s\n' "${case[@]}" | sed 's/../& /g' to get each number on a separate line and avoiding the space problem:

$ declare -a case=("060610" "080813" "101016" "121219" "141422")

$ printf '%s\n' "${case[@]}" | sed 's/../& /g'
06 06 10
08 08 13
10 10 16
12 12 19
14 14 22

If you want it back into an array, you can use mapfile

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.