Jimmy
Jimmy

Reputation: 881

BASH storing grep output into variable or array

I have two arrays: one is an array of CPU numbers and the other is an array of server names.

What I'm doing is searching a file to spit out the server name with the CPU number on the same line.

You can see the code below:

#!/bin/bash

cpu=("Atom" "Q8200" "Q9300" "Q9550" "i5" "i7" "X3440" "E3 1230" "Dell 860"
     "Dell r410" "Dell R200" "E5645" "E5504" "Dell 1950"
     "Dell 2950 Dual QuadCore Xeon E5420")
tknum=("tk676" "tk619" "tk20013" "tkc676" "tk74001")
for i in "${tknum[@]}" #being loop through tk numbers
do
        temp=$(grep -i -m 1 "$i" /home/jeremysd/public_html/servers.txt) #return line tknumber is on and store in variable
        #echo "$temp"
        echo "$i" #Print out the tk number
        for j in "${cpu[@]}" #begin loop through cpu numbers
        do
                echo "$temp" | grep -io "$j" #Return CPU number
        done
done

Now this works and places the information out like this:

sh array_test.sh
tk676
Q9550
tk619
Dell R200
tk20013
dell R410
tkc676
Q9550

That shows the server name and then CPU under it. However, I want it to be comma separated so that I can import it into a database

e.g:
tk676,q9550

Now, my thinking was to store the CPU type in a temporary variable and then echo it out, but doing so causes many blank lines to be entered into the string.

The loop through the CPU type becomes:

for j in "${cpu[@]}" #begin loop through cpu numbers
do
     temp1=$(echo "$temp" | grep -io "$j") #Return CPU number
     echo $temp1
done

The results are below and show extra blank lines. Anybody have any idea on how to store the CPU variables in a string or array without all the extra spaces being added?

sh array_test.sh
tk676



Q9550

Upvotes: 1

Views: 764

Answers (1)

Barmar
Barmar

Reputation: 780879

Check for an empty result:

if [ -n "$temp1" ]
then echo "$temp1"
fi

Upvotes: 2

Related Questions