I have an array of elements and I would like to find all elements that have the following form:
$i or ${i}
Where i can be any natural number? Can this be achieved without using AWK?
You can do this using grep if you prefer. For instance:
a=('$1' '$3' '$(4)' '5' 'a' '$a' '$1' '${52}')
for i in ${a[*]}; do
if [ $(echo "$i" | grep -E "^[$][0-9]+$") ]; then # First possible pattern
echo "$i"
elif [ $(echo "$i" | grep -E "^[$]{[0-9]+}$") ]; then # Second possible pattern
echo "$i"
fi
done
Output:
$1
$3
$1
${52}
#!/bin/bash
ARRAY=('a' '1' '$1' '${1}')
FOUND=()
for __ in "${ARRAY[@]}"; do
[[ $__ =~ ^[$]([0-9]+|[{][0-9]+[}])$ ]] && FOUND+=("$__")
done
echo "Found: ${FOUND[*]}"
Output:
Found: $1 ${1}
__, my favorite variable for iteration is A but before I had named the array as A so I decided to use __, then didn't bother to change it back to A when I finished. I don't think it's that difficult to comprehend as __ is explicitly declared in the for loop.for loop usage can comprehend that easily, but others might just think __ is a special variable to be used in for loop or a variable that gets values from array, similar to $_ variable in perl. You answer is clearly better than the accepted one so just wanted to offer my 2 cents. Nothing personal. :)