bash:将'\ n'分隔的字符串转换为数组 [英] bash: convert '\n' delimited strings into array

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

问题描述

我有这个脚本-

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

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

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