简体   繁体   English

BASH将grep输出存储到变量或数组中

[英]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. 我有两个数组:一个是CPU编号的数组,另一个是服务器名称的数组。

What I'm doing is searching a file to spit out the server name with the CPU number on the same line. 我正在做的是搜索文件以在同一行上吐出带有CPU编号的服务器名称。

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. 这将显示服务器名称,然后显示其下的CPU。 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. 现在,我的想法是将CPU类型存储在一个临时变量中,然后将其回显,但是这样做会使许多空白行输入到字符串中。

The loop through the CPU type becomes: 通过CPU类型的循环变为:

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? 有人对如何在不添加所有额外空格的情况下将CPU变量存储在字符串或数组中有任何想法吗?

sh array_test.sh
tk676



Q9550

Check for an empty result: 检查结果是否为空:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM