3

I have a scenario that I have to put lines of a file .txt inside an array, example of file content;

 type of host
 |
 |   first host
 |   |
 |   | second host
 |   | |     
 |   | |     same ip address 
 |   | |     |
HOST_A_B=192.168.0.1

I have to put this on array in bash

    #echo $Array[0]
    HOST_A=192.168.0.1
    #echo $Array[1]
    HOST_B=192.168.0.1

and sometimes the lines don't have a second HOST like

HOST_A_B=192.168.0.1
HOST_C=192.168.0.2
HOST_DEF_G=192.168.0.3

and the echo command output should looks like,

    #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

Any idea?

2
  • Are those lines with > Array pos the actual, literal output format you want? or are they some kind of abstract description of what you want? If the latter, then please add a sample of the actual output format. Also add a small but representative sample of your actual input file. Commented Apr 29, 2022 at 2:12
  • oh man, sorry, I have no idea what i wrote before. Commented Apr 29, 2022 at 3:45

1 Answer 1

5

Could be something like:

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
)

On your sample, that gives:

$ 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"
)

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.