Search and Replace Text in Multiple Files

To search and replace text in multiple files from the Linux command line, you can use a combination of the findgrepsed, and xargs commands. Here’s how you can do it:

Using find and sed with xargs


find /path/to/directory -type f -name "*.txt" -print0 | xargs -0 sed -i 's/oldtext/newtext/g'
    

Explanation:

  • find /path/to/directory -type f -name "*.txt": Finds all files ending with .txt in the specified directory and its subdirectories.
  • -print0: Prints the full file name on the standard output, followed by a null character (to handle filenames with spaces or special characters).
  • xargs -0: Reads items from the standard input, separated by null characters.
  • sed -i 's/oldtext/newtext/g': Uses sed to replace oldtext with newtext in each file (-i makes the change in-place).

Using grep to Find and sed to Replace


grep -rl 'oldtext' /path/to/directory | xargs sed -i 's/oldtext/newtext/g'
    

Explanation:

  • grep -rl 'oldtext' /path/to/directory: Recursively searches for files containing oldtext.
  • xargs sed -i 's/oldtext/newtext/g': Uses sed to replace oldtext with newtext in each found file.
Other Recent Posts