rgo1991
rgo1991

Reputation: 83

How can I prepend an array value to the start of specific lines in a text file

I want to prepend specific array values to the start of specific lines in a text file.

For example if I have an array animals=(cat, dog, bird, lizard) and a text file that looks like this:

.color
.age
.size
.breed
.name

.color
.age
.size

.color
.age
.size
.breed

How can I prepend cat to lines 1-5, dog to lines 6-8, bird to lines 9-13. (each animal has a different number of sections)

The output text file should look like this:

cat.color
cat.age
cat.size
cat.breed
cat.name

dog.color
dog.age
dog.size

Bird.color
Bird.age
Bird.size
Bird.breed

Any help is much appreciated :)

Upvotes: 0

Views: 68

Answers (2)

mickp
mickp

Reputation: 1819

Looks like blank line is the separator so we can use that:

a=(cat dog bird lizard)
i=0 ac=${#a[@]}

while IFS= read -r line; do
   [[ $line =~ ^$ ]] && { ((i = (i + 1) % ac)); printf '\n';  continue; }
   printf '%s\n' "${a[i]}$line"
done < file

Upvotes: 1

Armali
Armali

Reputation: 19395

How can i prepend cat to lines 1-5 then dog to lines 6-…

We can also abuse join to join on a nonexistent field:

join --nocheck-order -j2 <(printf %s\\n ${animals[*]}) <(head -5 text)|tr -d ' '

Upvotes: 0

Related Questions