Forrest logo
back to the grep tool

file_manipulation:warp:3dcc9

Recursively find and replace within a directory
$ grep -rl ${old_text} ${file_path} | xargs sed -i '' 's/${old_text}/${new_text}/g'
try on your machine

This command is used to replace occurrences of a specific text string (${old_text}) with a new text string (${new_text}) in multiple files.

Let's break down the command:

  1. grep -rl ${old_text} ${file_path}: This command searches for files within the specified file path that contain the text string ${old_text}. Here, -r stands for "recursive" (search subdirectories), and -l stands for "list" (display filenames instead of matching lines).

  2. | xargs: The pipe character "|" is used to redirect the output of the previous command to the next command. In this case, it passes the list of filenames returned by grep to the xargs command.

  3. sed -i '' 's/${old_text}/${new_text}/g': The sed command is a stream editor that performs text transformations. Here, it is used with the following options:

    • -i '': This option modifies the files in-place, i.e., the changes are made directly to the files.
    • 's/${old_text}/${new_text}/g': This is the substitution expression used by sed. It replaces all occurrences of ${old_text} with ${new_text}. The 'g' flag is used to replace all occurrences on each line, not just the first one.

Overall, this command searches for files containing ${old_text}, then using xargs it passes the filenames to sed to replace ${old_text} with ${new_text} in all the matching files.

This explanation was created by an AI. In most cases those are correct. But please always be careful and never run a command you are not sure if it is safe.
back to the grep tool