0

I am executing below script for search and replace in a file. search values assigned to a array S from a file Replace value assigned to another array R from a file. from the file it's replacing only last value instead of all values. what could be the mistake. If I use hard coded multiple sed command instead of loop it's working and without having assigned files.

#!/bin/bash
jmx_file_name=$1
S=( `cat "test.txt" `)
R=( `cat "test1.txt" `)
while [ $X -ge 0 ];
    do
    echo ${S[X]}
    echo ${R[X]}
    sed -i "s/${S[X]}/\${${R[X]}}/g" $jmx_file_name
    let X--;
   done
shellter
  • 36,525
  • 7
  • 83
  • 90
  • 3
    what is setting `X` with a beginning value? `X` will default to `0` (if your lucky), and `X--` will make its value `-1`. Also thinkin you might need `${S[$X]}`. AND all caps variables (except for system values) are considered poor style in any language except COBOL ;-) . Good luck. – shellter Jul 24 '18 at 15:08
  • 2
    Using Bash arrays for this is silly anyway, and keeping the patterns and the replacements in two separate files is crazy. Generate a single `sed` script from those files so you only need to process the target file once. Basically, `paste test.txt test1.txt | sed $'s#^#s/#;s#\t#/#;s#$#/g#' | sed -f - -i "$1"` – tripleee Jul 24 '18 at 15:52
  • 2
    and most importantly, don't do this with repeated calls to sed in a shell loop at all, just do it with 1 call to awk. See [why-is-using-a-shell-loop-to-process-text-considered-bad-practice](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice) for a discussion of some of the issues and see [is-it-possible-to-escape-regex-metacharacters-reliably-with-sed](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed/29626460#29626460) for some more and understand that there's even more... – Ed Morton Jul 24 '18 at 16:21

0 Answers0