Skip to content

Instantly share code, notes, and snippets.

@isaactzab
Last active November 8, 2019 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaactzab/db40c7d7a96c1ca0eae34767ffca4d14 to your computer and use it in GitHub Desktop.
Save isaactzab/db40c7d7a96c1ca0eae34767ffca4d14 to your computer and use it in GitHub Desktop.
Bash Scripting

Modify bash array items without looping

Original post from: http://codesnippets.joyent.com/posts/show/1826

replace any "ba" substring with "TT" in every array item

array=( foo babar baz )
array=( "${array[@]//ba/TT}" )
echo "${orig[@]}"$'\n'"${array[@]}"

replace only the first "ba" substring with "TT" in every array item

array=( foo babar baz )
array=( "${array[@]/ba/TT}" )
echo "${orig[@]}"$'\n'"${array[@]}"

orig=( foo bar baz )

append "foo" to every array item

array=( "${array[@]/%/foo}" )
echo "${orig[@]}"$'\n'"${array[@]}"

replace last char "r" with "foo"

array=( "${array[@]/%r/foo}" )
echo "${orig[@]}"$'\n'"${array[@]}"

prepend "foo" to every array item

array=( "${array[@]/#/foo}" )
echo "${orig[@]}"$'\n'"${array[@]}"

replace "ba" at the beginning with "foo"

array=( "${array[@]/#ba/foo}" )
echo "${orig[@]}"$'\n'"${array[@]}"

replace any array item matching "b*" with "foo"

array=( "${array[@]/%b*/foo}" )
echo "${orig[@]}"$'\n'"${array[@]}"

replace any array item matching "*z" with "foo"

array=( "${array[@]/#*z/foo}" )
echo "${orig[@]}"$'\n'"${array[@]}"

replace any array item matching "a" with "foo"

#array=( "${array[@]/%*a*/foo}" )
array=( "${array[@]/#*a*/foo}" )
echo "${orig[@]}"$'\n'"${array[@]}"

delete a single leading or trailing space from any array item

cf. http://codesnippets.joyent.com/posts/show/1816

array=( "${array[@]/# /}" )
array=( "${array[@]/% /}" )
echo "${orig[@]}"$'\n'"${array[@]}"

further Bash array tips

for positional parameters also see: http://codesnippets.joyent.com/posts/show/1706

get the first array item

array=( "${array[@]:0:1}" )
echo "${orig[@]}"$'\n'"${array[@]}"

get the last array item

array=( "${array[@]: -1}" )
echo "${orig[@]}"$'\n'"${array[@]}"

get all array items after the first one

array=( "${array[@]:1}" )
echo "${orig[@]}"$'\n'"${array[@]}"

get the second array item

array=( "${array[@]:1:1}" )
echo "${orig[@]}"$'\n'"${array[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment