I am trying to get specific information from a bunch of files.
Iterating over a list of files,grep
ing for what I need. I know for sure that each grep
will give more than 1 result and I want to store that result in an array. After finishing the work specific to file, I want to erase everything from arrays and start afresh for new file.
files_list=`ls`
for f in $files_list
do
echo $f
arr1=`cat $f | grep "abc" | grep "xyz"`
arr2=`cat $f | grep "pqr" | grep "mno"`
arr3=`cat $f | grep "df"`
for ((i=0; i<${#arr1[@]}; ++i))
do
printf "%s %s %s\n" "${arr1[i]}" "${arr2[i]}" "${arr3[i]}"
done
unset $arr1
unset $arr2
unset $arr3
done
So I used unset
to empty the array but it's giving error.
line 49: unset: `x': not a valid identifier
I don't want to delete a particular member/index of array but entire array itself. Can anyone tell me how to do it?
To check if a array is empty or not, we can use the arithmetic expansion syntax (( )) in Bash. In the example above, this syntax ${#arr[@]} returns the total number of elements in an array.
How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.
To really remove an exact item, you need to walk through the array, comparing the target to each element, and using unset to delete an exact match. Note that if you do this, and one or more elements is removed, the indices will no longer be a continuous sequence of integers.
Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"
unset
works with variable names, not the values they keep. So:
unset arr1
or, if you want to empty it:
arr1=()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With