Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash capturing output of awk into array

Tags:

arrays

linux

bash

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:

myarr=$(ps -u kdride | awk '{ print $1 }')

But that capture all my output into one giant string separated by commas:

output: PID 3856 5339 6483 10448 15313 15314 15315 15316 22348 29589 29593 32657 1

I also tried the following:

IFS=","
myarr=$(ps -u kdride | awk '{ print $1"," }')

But the output is: PID, 3856, 5339, 6483, 10448, 15293, 15294, 15295, 15296, 22348, 29589, 29593, 32657,
1

I want to be able to capture each individual pid into its own array element. Setting IFS = '\n' does not do anything and retains my original output. What change do I need to do to make this work?

like image 962
Paul Avatar asked Feb 27 '13 05:02

Paul


People also ask

How do I print output from awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

How do I echo an array in bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


2 Answers

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.

like image 172
kamituel Avatar answered Oct 20 '22 14:10

kamituel


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=)
like image 4
jarno Avatar answered Oct 20 '22 14:10

jarno