Linux 在 bash shell 的 for 循环内连接字符串变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9692804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:09:34  来源:igfitidea点击:

Concatenating string variable inside a for loop in the bash shell

linuxbashshell

提问by Obinwanne Hill

I have a file config.ini with the following contents:

我有一个包含以下内容的文件 config.ini:

@ndbd

I want to replace @ndbdwith some other text to finalize the file. Below is my bash script code:

我想@ndbd用其他一些文本替换来完成文件。下面是我的 bash 脚本代码:

ip_ndbd=(108.166.104.204 108.166.105.47 108.166.56.241)

ip_temp=""
for ip in $ip_ndbd
do
    ip_temp+="\n\[ndbd\]\nHostname=$ip\n"   
done
perl -0777 -i -pe "s/\@ndbd/$ip_temp/" /var/lib/mysql-cluster/config.ini

Basically, I just want to get all the ip addresses in a specific format, and then replace @ndbdwith the generated substring.

基本上,我只想获取特定格式的所有ip地址,然后@ndbd用生成的子字符串替换。

However, my for loop doesn't seem to be concatenating all the data from $ip_ndbd, just the first item in the list.

但是,我的 for 循环似乎并没有连接来自 的所有数据$ip_ndbd,只是连接列表中的第一项。

So instead of getting:

所以,而不是得到:

[ndbd]
HostName=108.166.104.204 

[ndbd]
HostName=108.166.105.47 

[ndbd]
HostName=108.166.56.241

I'm getting:

我越来越:

[ndbd]
HostName=108.166.104.204 

I'm pretty sure there's a better way to write this, but I don't know how.

我很确定有更好的方法来写这个,但我不知道如何。

I'd appreciate some assistance.

我很感激一些帮助。

Thanks in advance.

提前致谢。

采纳答案by evil otto

If you want to iterate over an array variable, you need to specify the whole array:

如果要遍历数组变量,则需要指定整个数组:

ip_ndbd=(108.166.104.204 108.166.105.47 108.166.56.241)

ip_temp=""
for ip in ${ip_ndbd[*]}
do
    ip_temp+="\n\[ndbd\]\nHostname=$ip\n"   
done

回答by Kent

i didn't see any usage of your file with content @ndbd...

我没有看到您的文件有任何使用内容@ndbd ...

is this what you want?

这是你想要的吗?

kent$  echo "108.166.104.204 108.166.105.47 108.166.56.241"|awk '{for(i=1;i<=NF;i++){print "[ndbd]";print "HostName="$i;print ""}}'
[ndbd]
HostName=108.166.104.204

[ndbd]
HostName=108.166.105.47

[ndbd]
HostName=108.166.56.241

you could just redirect the output to your config.ini file by > config.ini

您可以通过以下方式将输出重定向到您的 config.ini 文件 > config.ini

回答by ebutusov

Replace

代替

ip_ndbd=(108.166.104.204 108.166.105.47 108.166.56.241)

with

ip_ndbd="108.166.104.204 108.166.105.47 108.166.56.241"