Unix command to replace all instances of a string in every file in a folder [closed]
sed
in in-place mode along with find
should probably work:
find . -type f -exec sed -e 's/Test_Dbv3/TestDbv3/g' -i.bak '{}' +
The aptly named find
command finds files. Here, we're finding files in the current working directory (.
) that are files (-type f
). Using these files, we're going to -exec
a command: sed
. +
indicates the end of the command and that we'd like to replace {}
with as many files as the operating system will allow.
sed
will go file-by-file, line-by-line, executing commands we specify. The command we're giving it is s/Test_Dbv3/TestDbv3/g
, which translates to “substitute matches of the regular expression Test_Dbv3
with the text TestDbv3
, allowing multiple substitutions per line”. The -i.bak
means to replace the original file with the result, saving the unmodified version with the filename suffixed with .bak
.
s/_//g
is your regex assuming you want all _
gone; otherwise I need to guess how to specify your regex:
For example
s/^(Test|test)_/$1/g
to replacetest_
withtest
andTest_
withTest
if they are at the beginning of a line.Or
s/^(test)_/$1/gi
will additionally work for allTEST_
,tEsT_
, etc.If you decide to need completely case insensitive matching that is only available for the for
perl -pi -e 's/.../.../gi'
or GNUsed
or more but not thesed
command (not even variables like$1
are, are they?)If there are also filenames starting like
Test2_
or1EXPERIMENT_
and more words you may would uses/^([A-Za-z0-9]{3,10})_/$1/g
to match every combination of letters and numbers of length 3 to 10 chars, not just theTest
ortest
you mentioned.For even more specific regex search for "regex cheatsheet" and just don't wonder when single tools like
sed
orgrep
don't support everything should you even decide to use them.Should you also ever need a command to only rename files in a folder,but not edit their content you may try
rename 's/search/relace/' folder/*
(not matching subdirectories)orrename search replace folder/*
(depending on version of rename).