Sample Header Ad - 728x90

How can I take a sub-array in bash of the first N elements of a string array with elements containing spaces?

2 votes
1 answer
311 views
This question is similar to this one but it differs from it: Consider this array with string elements which may contain spaces: a@W:$ arr=("eins" "zwei" "eins plus zwei" "vier" "fünf") a@W:$ echo ${#arr[@]} # ok, 5 elements, as expected 5 a@W:$ echo ${arr} # the fourth one, indexing starts at 0 vier a@W:$ echo ${arr} # the third one, which contains two blancs eins plus zwei a@W:$ ar2=${arr[@]:0:3} # I only want the firs three of them a@W:$ echo ${ar2[@]} eins zwei eins plus zwei a@W:$ echo ${#ar2[@]} # but they are all glued together into one element 1 a@W:$ **What mus I do to prevent this gluing them all together?** The string containing spaces, "eins plus zwei" shall stay the third element.
Asked by Adalbert Hanßen (303 rep)
Mar 24, 2025, 12:47 PM
Last activity: Mar 24, 2025, 11:53 PM