I have list of 1000 files in a text file, can anyone tell me how to replace a word in all the 1000 files. I have placed all the text files names in the a text file. changes.txt
this is command I am using to replace a single file.
perl -pi.bak -e 's/apple/orange/' filename
cat changes.txt
file1
file2
files3
..
..
filen
file1 ,file2, file3 contain the word apple I need to replace to orange, I need to do in a single shot. any help please.
No, above command mentioned by you will not work, you need to remove single quote ' mentioned in RED color in quote section. Also it is always good practice to let people know about their suggestions if it worked for OP or not.
I think the below will work well, if you not like to replace the files on the same directory
while `read line`
do
sed 's/apple/orange/g' $line > <NewPath>/$line
done < changes.txt
the above can place the modified file in the newpath and the files in original files doesn't get override. since you are modifying 1000 files, if anything goes wrong you have a backup..
No. The above code will not work with any shell. Command substitution occurs in a subshell execution environment. Variables set in a subshell execution environment (by read line in this case) cannot affect the parent shell execution environment. So, assuming changes.txt is an existing, non-empty, text file, the 1st time through your loop will run the command:
sed 's/apple/orange/g' $line > <NewPath>/$line
which, with the expansion of the (unquoted) $line in two places, will expand to the command:
sed 's/apple/orange/g' > <NewPath>/
which will attempt to read the remainder of changes.txt , change all occurrences of apple on those lines to orange , and write the results to the directory named by <newpath>/. . If you aren't running as root, that will fail. If you are running as root (depending on the operating system and filesystem type that contains that director)y, it will either fail with an EBADF, EISDIR, or EPERM error; or it will destroy that directory and make all files that were in that directory inaccessible.