E
E
enabl32019-02-28 11:56:59
bash
enabl3, 2019-02-28 11:56:59

How to replace different strings with different data in a file?

Hello everyone, there is a conditional dock "file", it contains text in the following format:
16.
sometext16
19.
sometext19
Using this script:

num="16,19"
text="test1,test2"
for i in `echo $num | tr ',' '\n'`
    do
        textold=$(cat file | grep $i | tail -n 1)
        echo "Number #$i"
        echo "TEXT: oldtext$i"
printf "\n"
    done

I output it in the following form:
Number #16
TEXT: oldtext16
Number #19
TEXT: oldtext19
How in "file" to change the data for each "#" to the "$text" we need? I can't figure it out, when replacing with "sed" it changes the value in two lines to "test1,test2" The
desired output is as follows:
Number #16
TEXT: test1
Number #19
TEXT: test2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2019-02-28
@enabl3

Well, you can.
But your task is strange .. It would be radically redone.

num=( 16 19 )
text=( test1 test2 )
declare -i index=0

while [ -n "${num[$index]}" ]
do
  echo "DEBUG: $index, ${num[$index]}, ${text[$index]}"
  sed -i -r "s/^${num[$index]}\./#${num[$index]}/" file
  sed -i -r "s/^[^\d#].*${num[$index]}/TEXT:${text[$index]}/" file
  index+=1
done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question