skip to Main Content

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.

4

Answers


  1. 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.

    Login or Signup to reply.
  2. 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 '%sn' "${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))
    Login or Signup to reply.
  3. 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")'
    
    Login or Signup to reply.
  4. 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
    

    If array is a scalar

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

    you should use a parser. is useful for generic stream editing and is a parser specifically made to deal with JSON data.

    Here jq used to select only those values that contain at least 1 character and where all characters must be numbers using the ^[0-9]+$:

    readarray -t new_arr < <(echo "$array" | jq -r '.[] | select(test("^[0-9]+$"))')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search