Advertisements

#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:Y part is doing the slicing by taking a slice of length Y starting at position X. Note that if X is negative, that is we start at X elements from the end, we must put a space between the colon and the number.
Advertisements

About whitehatty

Computer Engineer and Scientist interested in Computer Security, Complex Networks, Math, Biology and Medicine. "Think Different" life style. Quake 3 Arena player. NERD by DNA.

Posted on February 5, 2019, in Linux and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: