Unix command to replace all instances of a string in every file in a folder [closed] Unix command to replace all instances of a string in every file in a folder [closed] unix unix

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 replace test_ with test andTest_ with Test if they are at the beginning of a line.

  • Or s/^(test)_/$1/gi will additionally work for all TEST_, tEsT_, etc.

  • If you decide to need completely case insensitive matching that is only available for the for perl -pi -e 's/.../.../gi' or GNU sed or more but not the sed command (not even variables like $1 are, are they?)

  • If there are also filenames starting like Test2_ or 1EXPERIMENT_ and more words you may would use s/^([A-Za-z0-9]{3,10})_/$1/g to match every combination of letters and numbers of length 3 to 10 chars, not just the Test or test you mentioned.

  • For even more specific regex search for "regex cheatsheet" and just don't wonder when single tools like sed or grep 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 tryrename 's/search/relace/' folder/* (not matching subdirectories)or rename search replace folder/* (depending on version of rename).