Skip to content

Instantly share code, notes, and snippets.

@wallentx
Created December 17, 2015 05:28
Show Gist options
  • Select an option

  • Save wallentx/b35e9ee14cf6f2520ba8 to your computer and use it in GitHub Desktop.

Select an option

Save wallentx/b35e9ee14cf6f2520ba8 to your computer and use it in GitHub Desktop.
Manipulating and parsing arrays in bash
#!/bin/bash
# Objective- print the following array in reverse order:
# var arr = (1,2,3,4)
# I buckled under pressure!
# Colors to make it pretty..
red=$(tput setaf 1)
grn=$(tput setaf 2)
yel=$(tput setaf 3)
blu=$(tput setaf 4)
res=$(tput sgr0)
# Prompt user for array elements
clear
echo -e "\n${blu}Please enter array elements (separated by spaces) and press enter${res}\n"
read your_string
IFS=$'\n' read -ra your_array <<< "$your_string"
echo -e "\nNew variable: ${yel}your_array${grn}=(${red}$your_array${grn})${res}\n"
sleep 1
echo -e "\nNow to print the array elements in reverse order\n"
echo -e "press any key to advance..."
read -r -n 1
echo -e "\nSolution using REV (reverses entire string)\n"
printf "%s\n" "${your_array[@]}" | rev
read -r -n 1
echo -e "\nSolution using SED:\n"
printf "%s\n" "${your_array[@]}" | sed -e :a -e 's/\([^ ]*\) \([^ ]*\)/\2_\1/;ta;s/_/ /g'
read -r -n 1
echo -e "\nSolution using a For Loop and SED:\n"
for i in "${your_array[@]}"; do
printf "%s\n" "$i" | sed -e :a -e 's/\([^ ]*\) \([^ ]*\)/\2_\1/;ta;s/_/ /g'
done
read -r -n 1
echo -e "\nSolution using awk\n"
printf "%s\n" "${your_array[@]}" | awk '{for (i=NF; i>1; i--) printf("%s ",$i); printf("%s\n",$1)}'
echo -e "\nNow let's count the elements in the array"
read -r -n 1
echo -e "\nCount occurances of elements\n"
for ((i=0; i<${#your_string[@]}; i++)); do
printf "%s\n" ${your_string[$i]} | sort -n | uniq -c | awk '{ print $2, $1 }'
done
read -r -n 1
echo -e "\nCount the elements in the array\n"
elements=$(wc -w <<< "${your_array[@]}")
echo -e "There are $elements elements in the array\n"
echo -e "All done!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment