我有一个场景,我必须将文件 .txt 的行放入数组中,文件内容的示例;
type of host
|
| first host
| |
| | second host
| | |
| | | same ip address
| | | |
HOST_A_B=192.168.0.1
我必须把它放在 bash 的数组中
#echo $Array[0]
HOST_A=192.168.0.1
#echo $Array[1]
HOST_B=192.168.0.1
有时这些线路没有第二个主机,例如
HOST_A_B=192.168.0.1
HOST_C=192.168.0.2
HOST_DEF_G=192.168.0.3
echo 命令输出应该如下所示:
#echo $Array[1]
HOST_A=192.168.0.1
#echo $Array[2]
HOST_B=192.168.0.1
#echo $Array[3]
HOST_C=192.168.0.2
#echo $Array[4]
HOST_DEF=192.168.0.3
#echo $Array[5]
HOST_G=192.168.0.3
任何想法?
答案1
可能是这样的:
readarray -t array < <(
awk '
match($0, /^HOST_[^=]+=/) {
host = substr($0, 1, RLENGTH - 1)
ip = substr($0, RLENGTH)
n = split(host, hosts, "_")
for (i = 2; i <= n; i++) print "HOST_"hosts[i] ip
}' < your-file
)
在你的样本上,这给出了:
$ typeset -p array
declare -a array=(
[0]="HOST_A=192.168.0.1"
[1]="HOST_B=192.168.0.1"
[2]="HOST_C=192.168.0.2"
[3]="HOST_DEF=192.168.0.3"
[4]="HOST_G=192.168.0.3"
)