DEV Community

Ron
Ron

Posted on

How to change a word across multiple files in a directory using find and sed

If you need to replace or update a word in multiple files within a directory, you can use command-line tools like find and sed to accomplish the task efficiently. Below is a method that demonstrates how to locate files, extract specific parts of their names, and make the desired changes.

Step-by-Step Command Explanation.


find ./directory -type f -name "*.filename.yml" -exec sh -c '

 for file; do

   # Extract the base name of the file without the extension
   what_you_want_to_change_to=$(basename "$file" .filename.yml)

   # Use sed to add a new line containing the replacement word
   sed -i "/name: $what_you_want_to_change_to/a replaces: '\''replace_me'\''" "$file"

 done

' sh {} +
Enter fullscreen mode Exit fullscreen mode

Key Components of the Command:

find ./directory: Searches within the specified directory.

-type f: Targets only files (ignores directories).

-name "*.filename.yml": Filters files based on their extension or pattern.

$(basename "$file" .filename.yml): Extracts the file name without its extension.

sed -i: Edits the files in place, adding the new content after the matched line.

replaces: '\''replace_me'\'': Appends a line in the format replaces: 'replace_me'.

Example Use Case
Suppose you have several .yml files, each containing a line like name: example. This script finds each file, extracts the file name, and appends a new line with a replacement value.

The final result in each file will look like this:
name: example
replaces: 'replace_me'

Why Use find and sed?
This method is efficient for batch processing multiple files and eliminates the need for manual editing. By combining find, a shell script, and sed, you gain:

  • Speed: Processes hundreds of files in seconds.
  • Precision: Only modifies files matching your criteria.
  • Scalability: Easily adaptable to different patterns and use cases.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay