加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

将输出重定向到bash数组

发布时间:2020-12-15 18:54:13 所属栏目:安全 来源:网络整理
导读:我有一个包含字符串的文件 ipAddress=10.78.90.137;10.78.90.149 我想将这两个IP地址放在一个bash数组中.为了达到这个目的,我尝试了以下几点: n=$(grep -i ipaddress /opt/ipfile | cut -d'=' -f2 | tr ';' ' ') 这导致提取值,但由于某些原因,数组的大小返
我有一个包含字符串的文件
ipAddress=10.78.90.137;10.78.90.149

我想将这两个IP地址放在一个bash数组中.为了达到这个目的,我尝试了以下几点:

n=$(grep -i ipaddress /opt/ipfile |  cut -d'=' -f2 | tr ';' ' ')

这导致提取值,但由于某些原因,数组的大小返回为1,我注意到这两个值都被标识为数组中的第一个元素.那是

echo ${n[0]}

回报

10.78.90.137 10.78.90.149

我该如何解决?

谢谢您的帮助!

你真的需要一个数组吗

庆典

$ipAddress="10.78.90.137;10.78.90.149"
$IFS=";"
$set -- $ipAddress
$echo $1
10.78.90.137
$echo $2
10.78.90.149
$unset IFS
$echo $@ #this is "array"

如果你想放入数组

$a=( $@ )
$echo ${a[0]}
10.78.90.137
$echo ${a[1]}
10.78.90.149

@OP,关于您的方法:将您的IFS设置为空格

$IFS=" "
$n=( $(grep -i ipaddress file |  cut -d'=' -f2 | tr ';' ' ' | sed 's/"//g' ) )
$echo ${n[1]}
10.78.90.149
$echo ${n[0]}
10.78.90.137
$unset IFS

此外,没有必要使用这么多工具.你可以使用awk,或者只是使用bash shell

#!/bin/bash
declare -a arr
while IFS="=" read -r caption addresses
do
 case "$caption" in 
    ipAddress*)
        addresses=${addresses//["]/}
        arr=( ${arr[@]} ${addresses//;/ } )
 esac
done < "file"
echo ${arr[@]}

产量

$more file
foo
bar
ipAddress="10.78.91.138;10.78.90.150;10.77.1.101"
foo1
ipAddress="10.78.90.137;10.78.90.149"
bar1

$./shell.sh
10.78.91.138 10.78.90.150 10.77.1.101 10.78.90.137 10.78.90.149

呆子

$n=( $(gawk -F"=" '/ipAddress/{gsub(/"/,"",$2);gsub(/;/," ",$2) ;printf $2" "}' file) )
$echo ${n[@]}
10.78.91.138 10.78.90.150 10.77.1.101 10.78.90.137 10.78.90.149

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读