Problem Statement
Explain advanced array operations including sorting, searching, filtering, and transforming arrays in bash.
Explanation
Array sorting: bash has no built-in sort, use external sort command:
```bash
ARRAY=(banana apple cherry)
IFS=$'\n' SORTED=($(sort <<< "${ARRAY[*]}"))
unset IFS
```
Reads array into sort, captures output into new array. Numeric sort: sort -n. Reverse: sort -r. For large arrays, write to file, sort, read back.
Searching arrays: loop through and compare:
```bash
contains() {
local item=$1
shift
for element in "$@"; do
[[ $element == "$item" ]] && return 0
done
return 1
}
contains "apple" "${ARRAY[@]}" && echo "Found"
```
For associative arrays, check key: [[ -v ASSOC[key] ]] tests if key exists.
Filtering arrays: create new array with matching elements:
```bash
ORIG=(apple banana apricot cherry)
FILTERED=()
for item in "${ORIG[@]}"; do
[[ $item == a* ]] && FILTERED+=("$item")
done
```
Filters items starting with 'a'. Use pattern matching, regex, or custom conditions.
Transforming arrays: apply operation to each element:
```bash
NUMS=(1 2 3 4 5)
SQUARES=()
for n in "${NUMS[@]}"; do
SQUARES+=($((n * n)))
done
```
Map operation creating new array. In-place: NUMS[i]=$(process "${NUMS[i]}").
Array joining: IFS=, joined="${ARRAY[*]}" joins with comma. Splitting: IFS=, read -ra ARRAY <<< "$string" splits string on comma. Removing elements: unset ARRAY[index] removes specific element (creates sparse array), or rebuild: NEW_ARRAY=(${ARRAY[@]:0:index} ${ARRAY[@]:$((index+1))}) removes element.
Array copying: COPY=("${ARRAY[@]}") creates shallow copy. Associative array: for key in "${!ASSOC[@]}"; do NEW_ASSOC[$key]=${ASSOC[$key]}; done. Understanding array operations enables complex data manipulation in pure bash.