0

I have a file that contains:

asd x    
sometihng else    
asd x    
sometihng else    
asd x

and an array that contains values=(3,4,5). And now I want to replace the "x" on the first line in the file, with the value of the first element in the vector from a shell script. For all lines/elements. Such that I get

asd 3
sometihng else
asd 4
sometihng else
asd 5

How should I do this?

As of now, I tried using sed in a loop. Something like this:

values=(3 4 5)
lines=3
for currentLine in $(seq $lines)
do
     currentElement=$(expr "$currentLine" / "2")
     sed "$currentLine s/\(asd\)\(.*\)/\1 ${values[$currentElement]}/"
done

But for every run through the loop I get the entire original file with the interesting line edited, like so:

asd 3
sometihng else    
asd x    
sometihng else    
asd x

asd x
sometihng else    
asd 4    
sometihng else    
asd x

asd x
sometihng else    
asd x    
sometihng else    
asd 5

Thanks, Alex

1 Answers1

0

It would be easier to use awk:

awk 'BEGIN { a[1]=3; a[2]=4; a[3]=5; } /x/ { count++; sub(/x/, a[count]); } { print }'

If you insist on sed, however, you could try something like this:

{ echo "3 4 5"; cat some_file; } | \
    sed '1{h;d};/x/{G;s/x\(.*\)\n\([0-9]\).*/\1\2/;x;s/^[0-9] //;x}'
Michael Vehrs
  • 3,293
  • 11
  • 10