Efficiently Finding and Replacing Text in Multiple Files Using ripgrep and sed
Andrej Bartko
2 min read
command
rg "some string" | xargs -d "\n" sed -i "s/some string/another string/g"
The command searches for the specified string using ripgrep and pipes the results to xargs, which executes the sed command on each line returned by ripgrep. The sed command then replaces each occurrence of "find-string" with "new string" in the specified files.
Here's the breakdown of the command:
rg "find-string"
: This uses ripgrep to search for the string "find-string" in the current directory and all its subdirectories.|
: This pipes the output of the previous command (the list of files containing "find-string") to the next command.xargs -d "\n"
: This takes the output from the previous command and passes it as arguments to the sed command. The -d option narrows down the delimiter to a newline character, so that each line returned by ripgrep is passed as a separate argument to sed. By default it uses new line characters as well as spacessed -i "s/find-string/new string/g"
: This is the sed command, which replaces each occurrence of "find-string" with "new string" in the specified files. The -i option tells sed to edit the files in-place, so the changes are saved directly to the original files. The s command is the substitute command, which performs search and replace operations on the specified files. The g flag at the end tells sed to replace all occurrences of the search string, rather than just the first one.
Links
0
Subscribe to my newsletter
Read articles from Andrej Bartko directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by