Bash capturing output of awk into array

后端 未结 2 400
我寻月下人不归
我寻月下人不归 2020-12-23 09:38

I am stuck on a little problem. I have a command which pipes output to awk but I want to capture the output of to an array one by one.

My example:

my         


        
相关标签:
2条回答
  • 2020-12-23 10:27

    Add additional parentheses, like this:

    myarr=($(ps -u kdride | awk '{ print $1 }'))
    
    # Now access elements of an array (change "1" to whatever you want)
    echo ${myarr[1]}
    
    # Or loop through every element in the array
    for i in "${myarr[@]}"
    do
       :
      echo $i
    done
    

    See also bash — Arrays.

    0 讨论(0)
  • 2020-12-23 10:27

    Use Bash's builtin mapfile (or its synonym readarray)

    mapfile -t -s 1 myarr < <(ps -u myusername | awk '{print $1}')
    

    At least in GNU/Linux you can format output of ps, so no need for awk and -s 1

    mapfile -t myarr < <(ps -u myusername -o pid=)
    
    0 讨论(0)
提交回复
热议问题