Skip to content

Latest commit

 

History

History
104 lines (67 loc) · 2.57 KB

02.Array_manipulation.md

File metadata and controls

104 lines (67 loc) · 2.57 KB

Array Manipulation in Linux Scripting

Array manipulation in Linux scripting involves performing various operations on arrays to modify, extract, or combine their elements. This tutorial will guide you through common array manipulation techniques in a Linux environment.

Creating and Initializing Arrays

Arrays can be created and initialized using various methods, as discussed in the previous tutorial. Let's briefly recap:

# Method 1: Using parentheses
my_array=("value1" "value2" "value3")

# Method 2: Using the `declare` command
declare -a my_array=("value1" "value2" "value3")

Appending Elements to Arrays

To add elements to the end of an array, you can use the += operator:

# Append a single element
my_array+=("value4")

# Append multiple elements
my_array+=("value5" "value6")

Removing Elements from Arrays

Elements can be removed from an array using the unset command:

# Remove the element at index 2
unset my_array[2]

# Remove all elements
unset my_array

Updating Array Elements

To update the value of a specific element in an array, simply assign a new value to that element:

# Update the element at index 1
my_array[1]="new_value"

Searching for an Element in an Array

You can search for a specific element in an array using a loop:

search_element="value2"

for element in "${my_array[@]}"; do
    if [[ "$element" == "$search_element" ]]; then
        echo "Element found: $search_element"
        break
    fi
done

Sorting Arrays

Sorting elements in an array can be done using the sort command:

sorted_array=($(for element in "${my_array[@]}"; do echo "$element"; done | sort))

Merging Arrays

Arrays can be merged by concatenating them:

array1=("apple" "banana")
array2=("cherry" "date")

merged_array=("${array1[@]}" "${array2[@]}")

Reversing Arrays

To reverse the order of elements in an array, you can use a loop:

reversed_array=()
for ((i=${#my_array[@]}-1; i>=0; i--)); do
    reversed_array+=("${my_array[i]}")
done

Conclusion

Array manipulation is a powerful feature in Linux scripting, allowing you to dynamically modify and interact with sets of data. Whether you need to add, remove, or search for elements, understanding array manipulation techniques is essential for writing efficient and flexible scripts. Incorporate these techniques into your scripts to handle arrays effectively in a variety of scenarios.