sed text replacement

Hello,

I'm using Bash and Sed to replace text within a text file (1.txt) twice in one script. Using a for loop I'm initially replacing any 'apple' words with the variable 'word1' ("leg). I'm then using another for loop to replace any 'apple' words with the variable 'word2' ("arm"). This task is dependent on the text file 'resetting' it's contents back to it's original form prior to the second for loop; otherwise the second text changes cannot be made. My issue is, the text file does not reset; within the script it keeps the new text replacements.

#!/bin/sh

word1="leg"
word2="arm"

for i in '1.txt';
do
	sed -e 's@apple@'$word1'@g' $i;
done

cat 1.txt

for i in '1.txt';
do
	sed -e 's@apple@'$word2'@g' $i;
done

Is there any way to reset the contents of the text file back to it's original content during a script? I am aware that the argument '-e' only temporarily changes a file's contents, but the file's contents only reset when a script has finished.

With a text file containing only one word 'apple', I expect the above script to replace the the word 'apple' with the word 'arm'. Only, for reasons described above, it is currently only changing to 'leg'.

Thanks,
F

What is your intention? First changing to leg then to arm does not make sense: you can directly change to arm.
Please give an example input and expected output.

Do you? Your script's "shebang" tells otherwise:

#!/bin/sh

Actually, the original file itself isn't touched in any way. While sed offers the -i ("in-place") option to overwrite the original file, you don't use it in your script.

Really? I'd expect the output (to stdout) of your script above to be

  • the contents of 1.txt with "apple" replaced with "leg"
  • the contents of 1.txt
  • the contents of 1.txt with "apple" replaced with "arm"

I don't think so - make a working copy and use that.

1 Like