1

I have text file like this:

src_dir=source1
src_dir=source2
dst_dir=dest1
whatever_thing=thing1
whatever_thing=thing2

I want a script that will create arrays with names from the left part of a line and fill it with elements from the right part of a line. So basically it should do:

src_dir=(source1 source2)
dst_dir=(dest1)
whatever_thing=(thing1 thing2)

I've tried so far:

while read -r -a line
do
    IFS='= ' read -r -a array <<< "$line"
    "${array[0]}"+="${array[1]}"
done < file.txt

2 Answers 2

2

If your bash version is 4.3 or newer, declare has an -n option to define a rerefence to the variable name which works as a reference in C++. Then please try the following:

while IFS== read -r key val; do
    declare -n name=$key
    name+=("$val")
done < file.txt

# test
echo "${src_dir[@]}"
echo "${dst_dir[@]}"
echo "${whatever_thing[@]}"
Sign up to request clarification or add additional context in comments.

3 Comments

@Inian Thanks for the suggestion. I've updated my answer accordingly.
Also I wouldn't call name references as pointers, they are more analogous to references in C++
@Inian I agree. Thanks again.
0

try this:

#!/bin/bash
mapfile -t arr < YourDataFile.txt
declare -A dict
for line in "${arr[@]}"; do
    key="${line%%=*}"
    value="${line#*=}"
    [ ${dict["$key"]+X} ] && dict["$key"]+=" $value" || dict["$key"]="$value"
done

for key in "${!dict[@]}"; do
    printf "%s=(%s)\n" "$key" "${dict["$key"]}"
done

explanation

# read file into array
mapfile -t arr < YourDataFile.txt

# declare associative array
declare -A dict

# loop over the data array
for line in "${arr[@]}"; do

    # extract key
    key="${line%%=*}"

    # extract value
    value="${line#*=}"

    # write into associative array
    #   - if key exists ==> append value
    #   - else initialize entry
    [ ${dict["$key"]+X} ] && dict["$key"]+=" $value" || dict["$key"]="$value"
done

# loop over associative array
for key in "${!dict[@]}"; do

    # print key=value pairs
    printf "%s=(%s)\n" "$key" "${dict["$key"]}"
done

output

dst_dir=(dest1)
src_dir=(source1 source2)
whatever_thing=(thing1 thing2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.