Home > Mobile >  How to extract numerical value from array of string in bash
How to extract numerical value from array of string in bash

Time:12-28

If array = ["stack","overflow","5","6","question","9"]

I want to make another array to store all numerical values like: new_arr = [5,6,9] in bash.

CodePudding user response:

This is how you can do in bash:

# declare original array
arr=("stack" "overflow" "5" "6" "question" "9")

# remove all elements that have at least one non-digit character
narr=(${arr[@]//*[!0-9]*})

# check content of narr
declare -p narr

Output:

declare -a narr='([0]="5" [1]="6" [2]="9")'

CodePudding user response:

In pure bash with comments inline:

#!/bin/bash

# the initial array
array=( "stack" "overflow" "5" "6" "question" "9" )

# declare the final array
declare -a new_arr

# loop over the original values
for val in "${array[@]}"
do
    # use regex to filter out those with only digits
    if [[ $val =~ ^[0-9] $ ]];
    then
        # and append them to new_arr
        new_arr =($val)
    fi
done

# print the result
for val in "${new_arr[@]}"
do
    echo $val
done

CodePudding user response:

With a for loop you will be able to go through your array and then, get inspiration with this post to determine if your iterator's value is a number or a string.

In case of a numerical value, just append it to another array.

CodePudding user response:

With :

The proper tool for your proper input:

array = ["stack","overflow","5","6","question","9"]
#!/bin/bash

arr=( $(
    node<<EOF
    new_arr = ["stack","overflow","5","6","question","9"]
    .filter(e => e.match(/^\d $/));
    new_arr.forEach(e => console.log(e))
EOF
)) 
printf '%s\n' "${arr[@]}" # plain bash array

Online test

new_arr = ["stack","overflow","5","6","question","9"]
.filter(e => e.match(/^\d $/));
new_arr.forEach(e => console.log(e))

Output

5
6
9
  • Related