如何在保留空字符串的同时解析Bash中换行符分隔的数据?

时间:2015-03-03 22:57:41

标签: linux bash shell

我之前发过了类似的问题,但我对人们对awkIFS

的所有变通方法感到困惑

我使用snmpbulkwalk来获取一串数据。 SNMP utils通常将请求的数据作为字符串返回,并在每个值之间用换行符进行分隔。

我可以将0到300+的值作为单个字符串。每个值后跟一个换行符。如果SNMP从其目标中获得一个空字符串,它会将换行符载体连接到空字符串,并将其添加到将被传回的数据中。我可以得到

  

10.1.1.1 \ n10.1.1.2 \ n10.1.1.3 \ n10.1.1.4 \ n(四个值)

     

以及

     

\ n \ n10.1.1.3 \ n10.1.1.4 \ n \ n \ n \ n10.1.1.8 \ n \ n(九个值)

以前我用它来解析数据:

IP=`echo $IP | tr "\n" " "`
IP=( $IP )

上面的代码会移除所有换行符。如果我使用了代码段,它将返回

  

字符串1:{" 10.1.1.1"," 10.1.1.2"," 10.1.1.3"," 10.1.1.4 "}

     

字符串2:{" 10.1.1.3"," 10.1.1.4"," 10.1.1.8"}

字符串1被正确解析为数组但字符串2未被解析。我需要它:

  

字符串2:{"",""," 10.1.1.3"," 10.1.1.4",& #34;","",""," 10.1.1.8",""}

我该如何做到这一点?

1 个答案:

答案 0 :(得分:2)

有关从bash中的文件或流中读取的最佳做法,请参阅BashFAQ #001。如果需要将内容读入数组,可能如下所示:

results=( )                       # declare the empty array
while IFS= read -r line; do       # loop over input lines...
  results+=( "$line" )            # ...appending just-read line to the array
done < <(snmpbulkwalk ...)        # ...reading output from snmpbulkwalk
declare -p results                # print the array's contents

...或者,使用bash 4.0 mapfile命令(或其同义词readarray)来获得相同的结果:

readarray -t results < <(snmpbulwalk ...)
declare -p results # print the array's contents

...之后您可以迭代"${snmp_results[@]}"或查看"${#snmp_results[@]}"以获取行数和索引。


后一种情况对您来说可能非常有用,因为您可以将两个结果读入两个不同的数组并并行索引。

readarray -t snmp_results_FOO < <(snmpbulwalk ... FOO)
readarray -t snmp_results_BAR < <(snmpbulwalk ... BAR)
for idx in "${!snmp_results_FOO[@]}"; do
  printf '%s,%s\n' "${snmp_results_FOO[$idx]}" "${snmp_results_BAR[$idx]}"
done