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

Do your career a favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Top comments (1)

Collapse
 
oto profile image
oto •

ok,thank you

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay