#Linux : How to Slice an Array in #Bash
A lot of things can be done using just the command line.
In fact, Bash shell scripting language is a touring-complete language, so anything can be done!
One important feature is the ability to slice an array (i.e. select a contiguous subset of elements of a collection).
So let’s say for example we stored the list of installed packages into a variable PACKAGE_LIST as a bash array:
#PACKAGE_LIST=(`dpkg -l | awk '{print $2}'`)and for some reason we want to select elements from 4 to 10:
#PACKAGE_LIST=${PACKAGE_LIST[@]:3:10}Let me explain. Here, we are using Bash parameter expansion:
-
The
[@]following the array name returns the whole content of the array. - The
:X:Ypart is doing the slicing by taking a slice of lengthYstarting at positionX. Note that ifXis negative, that is we start atXelements from the end, we must put a space between the colon and the number.
Posted on February 5, 2019, in Linux and tagged command line, linux, script bash. Bookmark the permalink. Leave a comment.
Leave a comment
Comments 0