将多行字符串转换为数组 [英] Convert multiline string to array

查看:23
本文介绍了将多行字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本:

nmapout=`sudo nmap -sP 10.0.0.0/24`
names=`echo "$nmapout" | grep "MAC" | grep -o '(.\+)'`
echo "$names"

现在 $names 变量包含用换行符分隔的字符串:

now the $names variable contains strings delimited with newlines:

>_
 (Netgear)
 (Hon Hai Precision Ind. Co.)
 (Apple)

我尝试使用子字符串方法进行数组转换:

I tried to do the array conversion with the sub-string approach:

names=(${names//\\n/ })
echo "${names[@]}"

但问题是,如果我运行此循环,我将无法通过索引(即 ${names[$i] 等)访问它们

But the problem is that I can't access them by indexing (i.e., ${names[$i] etc.), if I run this loop

for (( i=0; i<${#names[@]}; i++ ))
do
     echo "$i: ${names[$i]"
     # do some processing with ${names[$i]}
done

我得到这个输出:

>_
 0: (Netgear)
 1: (Hon
 2: Hai

但我想要的是:

>_
 0: (Netgear)
 1: (Hon Hai Precision Ind. Co.)
 2: (Apple)

我想不出一个好的方法来做到这一点,请注意第二个字符串中有空格.

I could not figure out a good way to do this, please note that the second string has spaces in it.

推荐答案

设置 IFS.Shell 使用 IFS 变量来确定字段分隔符是什么.默认情况下,IFS 设置为空格字符.将其更改为换行符.

Set IFS. Shell uses IFS variable to determine what the field separators are. By default IFS is set to the space character. Change it to newline.

#!/bin/bash
names="Netgear
Hon Hai Precision Ind. Co.
Apple"

SAVEIFS=$IFS   # Save current IFS
IFS=$'\n'      # Change IFS to new line
names=($names) # split to array $names
IFS=$SAVEIFS   # Restore IFS

for (( i=0; i<${#names[@]}; i++ ))
do
    echo "$i: ${names[$i]}"
done

输出

0: Netgear
1: Hon Hai Precision Ind. Co.
2: Apple

这篇关于将多行字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆