0

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?

2 Answers 2

2

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}
Sign up to request clarification or add additional context in comments.

Comments

2
#!/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}

3 Comments

Any particular reason for using an obfuscated variable name? Will probably confuse a lot of newbies.
@jaypal Besies __, 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.
True, for someone aware of 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. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.