هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.
$ مستخدم عادي# بصلاحية root (أو مع sudo)
The quick answer
grep -rlF 'db-old.example.com' /opt/app/config
sed -n 's/db-old\.example\.com/db-new.example.com/gp' /opt/app/config/app.yml
grep -rlZF 'db-old.example.com' /opt/app/config | xargs -0 sed -i.bak 's/db-old\.example\.com/db-new.example.com/g'
grep -rnF 'db-new.example.com' /opt/app/config1 list the files, 2 preview one file, 3 change all (with .bak backups), 4 check.
Step by step
- Find the files (
-lnames only,-Fplain text,-Znull-separated for safe names with spaces):
grep -rlF 'db-old.example.com' /opt/app/config- Preview —
-n … pprints only the changed lines, changes nothing:
sed -n 's/db-old\.example\.com/db-new.example.com/gp' /opt/app/config/app.yml
host: db-new.example.com- Escape special characters in the search part:
.→\.,[→\[,*→\*. Use another delimiter when the text has slashes:
sed -i 's#/var/www/old#/srv/www/new#g' site.conf- Change all files, with a backup (
-i.bakkeepsfile.bak):
grep -rlZF 'db-old.example.com' /opt/app/config | xargs -0 sed -i.bak 's/db-old\.example\.com/db-new.example.com/g'- Review and clean up:
for f in $(find /opt/app/config -name '*.bak'); do diff -u "$f" "${f%.bak}"; done | less
find /opt/app/config -name '*.bak' -delete- In a Git repo — no
.bakneeded, Git is the backup, andgit diffshows everything:
git grep -lz 'registry.old.example.com' | xargs -0 sed -i 's/registry\.old\.example\.com/registry.example.com/g'
git diff --stat- Only on some lines — an address before
s:
sed -i '/^\s*image:/ s/:1\.4\.2/:1.4.3/' deploy.yamlCheck that it worked
Common problems
| Problem | Cause | Fix |
|---|---|---|
sed: -e expression … unknown option to 's' | The text has / in it. | Use another delimiter: s#a#b#g. |
| More was changed than wanted | . in the pattern matches any character. | Escape dots (\.); use -w-like anchors or line addresses. |
| Files with spaces break the command | xargs without null separators. | grep -Z + xargs -0. |
sed: 1: "…": invalid command code on macOS | BSD sed needs an argument after -i. | sed -i '' 's/a/b/g', or install GNU sed (gsed). |
| File owner or SELinux label changed | sed -i writes a new file. | Check with ls -lZ; restorecon; use --follow-symlinks for links. |
| A YAML/JSON file broke | Quotes or indentation changed. | For structured files use yq/jq, then validate. |
Go further
- Command pages: sed, grep, xargs, yq.
- Next how-tos: Search text in many files, Read JSON in the shell with jq, Compare two files or folders.
- Learn it: RHCSA — sed, TLCL — sed, envsubst and yq in DevOps.
1How do you see what sed would change before changing files?
sed -n 's/old/new/gp' FILE prints only the changed lines.
2The text to replace contains slashes. What do you do?
Use another delimiter, for example s#old/path#new/path#g.