Hello Linux community,
I made a script that replaces strings in a file but it behaves very strangely because it worked a few times, but it doesn't most of the time, it just doesn't change the strings. I know that my script is working fine, otherwise it wouldn't have worked. And I have no error in the shell, nothing suspicious.
Note that the sed command doesn't work only in the while loop, maybe there's something wrong about this...
Here's an example of what I want to do : the file A contains "water" in the 1st line, and "milk" in the 2nd line. Running the script will replace all "water" strings in file B by "milk".
Again, I'm pretty sure that my script is okay, I didn't change anything after getting it to work. I checked the file paths, I tried to change the content of file A and file B, I spent hours to find what's wrong. That just doesn't make sense. Here's the script :
Do you have any idea, or could you at least try the script and tell me if it works for you?
I made a script that replaces strings in a file but it behaves very strangely because it worked a few times, but it doesn't most of the time, it just doesn't change the strings. I know that my script is working fine, otherwise it wouldn't have worked. And I have no error in the shell, nothing suspicious.
Note that the sed command doesn't work only in the while loop, maybe there's something wrong about this...
Here's an example of what I want to do : the file A contains "water" in the 1st line, and "milk" in the 2nd line. Running the script will replace all "water" strings in file B by "milk".
Again, I'm pretty sure that my script is okay, I didn't change anything after getting it to work. I checked the file paths, I tried to change the content of file A and file B, I spent hours to find what's wrong. That just doesn't make sense. Here's the script :
Code:
#!/bin/bash
fileA=~/Documents/a.txt #contains strings matchings
fileB=~/Documents/b.txt #strings to edit
linenum=4
i=1 #starts at line 1 in fileA
while [ $i -le $linenum ]
do
oldname=$(sed "$i q;d" $fileA) #takes string from line i in file A
let "i += 1"
newname=$(sed "$i q;d" $fileA) #takes string from line i+1 in file A
oldname=$(echo "${oldname}" | sed -e 's/[]$.*[\^]/\\&/g' )
#removes regex in the strins by adding a space
sed -i "s/${oldname}/${newname}/g" $fileB
#searches the string oldname in fileB and replace it with newname
let "i += 1"
done
Do you have any idea, or could you at least try the script and tell me if it works for you?