Manuel
Manuel

Reputation: 29

Store file content into arrays

What i'm trying to do is to take content form the file "test" modify it and display it again.

So the test file looks like this:

test
test.com

And i want to modify it, so it would look like this:

DNS.1 = test
DNS.2 = test.com

so i am trying to it with something like this:

$(i=1
for alt in "${alts[@]}"; do
    echo "DNS.$((i++)) = $alt"
done)

I just don't have an idea how i could take the content from a file and connect it with the code right above.

Does someone has an idea how it could work or knows where i can search for that problem.

Upvotes: 0

Views: 44

Answers (1)

Socowi
Socowi

Reputation: 27360

As pointed out in the comments, there are better ways than a loop when your input is a file. However, if you really want an array use mapfile:

< file mapfile -t alts

echo "array alts has ${!alts[@]} entries"
echo "the entries are"
printf '"%s\n"' "${alts[@]}"

By the way: Cyrus' awk script can also be used when your input is not a file but just an array:

# for files
awk '{print "DNS." NR " = " $0}' file
# for arrays (use only if your input is not a file)
(IFS=$'\n'; awk '{print "DNS." NR " = " $0}' <<< "${array[*]}")
# or
awk '{print "DNS." NR " = " $0}' < <(printf %s\\n "${array[@]}")

Upvotes: 1

Related Questions