1

Hi there.

I am very new to Shell Script so need your help...

I have config file with below info

    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

And inside my bash file, there's arraylist with below info

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

I want to change config file and save as below

    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

I tried awk and sed but no luck..... Could you please help this?

Kiokio
  • 19
  • 1
  • 2
    How did the shell arrays get populated? Chances are you don't need them and could instead take input directly from whatever they're being populated from so blindly building on top of them isn't a great idea. – Ed Morton Jul 04 '19 at 18:30
  • 1
    If the values are always `value11111`, `value22222`, etc.. you can use `awk` to generate the replacements. If they are arbitrary values, then you will need to use a script and a parameter expansion. `awk` and `sed` may be used, but in that case you will be spawning an additional process for each replacement. Provide an answer to the comment by @EdMorton – David C. Rankin Jul 05 '19 at 03:32

1 Answers1

0

Check out some of these answers.

I second the advice by Ed and David (and in hindsight, this whole post could have been a comment instead of an answer), that awk/sed might not be the best tool for this job, and you'd want to take a step back and re-think the process. There's a whole bunch of things that could go wrong; the array values might not be populated correctly, there's no check that enough values for all substitutions exist, and in the end, you can't roll changes back.

Nevertheless, here's a starting point, just to illustrate some sed. It certainly is not the most performant one, and only works for GNU sed, but provides the output you required

#!/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
hyperTrashPanda
  • 838
  • 5
  • 18