DEV Community

webduvet
webduvet

Posted on

3 1

Efficiently Finding and Replacing Text in Multiple Files Using ripgrep and sed

subtitle

Convenient way to search for and replace text in multiple files using the powerful ripgrep and sed tools

command

rg "some string" | xargs -d "\n" sed -i "s/some string/another string/g"
Enter fullscreen mode Exit fullscreen mode

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 spaces
  • sed -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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (1)

Collapse
 
oto profile image
oto

ok,thank you

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more