如何将配置文件中的相同单词替换为数组中的不同单词

时间:2019-07-04 18:20:14

标签: bash shell awk sed

你好。

我对Shell Script非常陌生,因此需要您的帮助...

我的配置文件包含以下信息

    config name AAAAA
    root root
    port number 00000
    Hostname hahahahah

    config name AAAAA
    root less
    port number 00001
    Hostname nonononono

    config name AAAAA
    root less
    port number 00002
    Hostname nonononono

在我的bash文件中,有一个数组列表,其中包含以下信息

${array1[0]} # Has value of value11111
${array2[1]} # Has value of value22222
${array2[1]} # Has value of value33333

我想更改配置文件并保存如下

    config name value11111
    root root
    port number 00000
    Hostname hahahahah

    config name value22222
    root less
    port number 00001
    Hostname nonononono

    config name value33333
    root less
    port number 00002
    Hostname nonononono

我尝试了awk并执行了sed操作,但是没有运气.....您能帮忙吗?

1 个答案:

答案 0 :(得分:0)

查看一些of these的答案。

我第二次接受了Ed和David的建议(事后看来,整篇文章可能只是评论而不是答案),awk / sed可能不是这项工作的最佳工具,而您想退后一步,重新思考该过程。有很多事情可能出问题;数组值可能未正确填充,无法检查是否存在足够用于所有替换的值,最后,您无法回滚更改。

尽管如此,这只是一个起点,只是为了说明一些sed。它当然不是性能最高的,并且仅适用于GNU sed,但可以提供所需的输出

#!/bin/bash

declare -a array
array=(value11111 value22222 value33333)

for a in "${array[@]}"; do
    # Use sed inline, perform substitutions directly on the file
    # Starting from the first line, search for the first match of `config name AAAAA`
    #   and then execute the substitution in curly brackets
    sed -i "0,/config name AAAAA/{s/config name AAAAA/config name $a/}" yourinputconfigfile
done
# yourinputconfigfile

    config name value11111
    root root
    port number 00000
    Hostname hahahahah

    config name value22222
    root less
    port number 00001
    Hostname nonononono

    config name value33333
    root less
    port number 00002
    Hostname nonononono