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 {} +
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.
Top comments (0)