linux批量查找并替换文件中的字符串
```bash grep -rl '/images/favicon.ico' . | xargs sed -i 's#/images/favicon.ico#/favicon.ico#g' ``` ### 命令拆解 1. **`LC_ALL=C`** 强制使用 C 语言环境(字节级别处理),让 `grep` 搜索速度更快,同时避免中文等多字节字符带来的意外问题。 2. **`fgrep -rl '/images/fa' .`** 在当前目录(`.`)下**递归搜索**包含字符串 `/images/fa` 的文件: - `-r` = 递归子目录 - `-l` = 只输出**文件名**(不显示具体匹配行) - `fgrep` = 固定字符串匹配(不走正则,纯文本搜索) 3. **`| xargs sed -i 's#/images/fa/#/fa#g'`** 对上一步找到的每一个文件,执行**原地替换**: - `-i` = 直接修改文件内容(in-place) - `s#/images/fa/#/fa#g` = 把文件中**所有** `/images/fa/` 替换为 `/fa` - 用 `#` 代替传统的 `/` 作为分隔符,避免路径中的 `/` 需要转义 推荐查看天气:http://www.362tq.com/beijing/ 推荐查看北京天气:http://www.362tq.com/beijing/zuotian.html 推荐查看北京7天天气:http://www.362tq.com/beijing/7tian.html 推荐查看北京10天天气:http://www.362tq.com/beijing/10tian.html 推荐查看北京15天天气:http://www.362tq.com/beijing/15tian.html 推荐查看北京40天天气:http://www.362tq.com/beijing/40tian.html 推荐查看天气:http://www.362tq.com/dongcheng/ 推荐查看天气:http://www.362tq.com/dongcheng/zuotian.html 推荐查看天气:http://www.362tq.com/dongcheng/7tian.html 推荐查看天气:http://www.362tq.com/dongcheng/10tian.html 推荐查看天气:http://www.362tq.com/dongcheng/15tian.html 推荐查看天气:http://www.362tq.com/dongcheng/40tian.html 推荐查看天气:http://www.362tq.com/xicheng/ 推荐查看天气:http://www.362tq.com/xicheng/zuotian.html 推荐查看天气:http://www.362tq.com/xicheng/7tian.html 推荐查看天气:http://www.362tq.com/xicheng/10tian.html 推荐查看天气:http://www.362tq.com/xicheng/15tian.html 推荐查看天气:http://www.362tq.com/xicheng/40tian.html 推荐查看天气:http://www.362tq.com/chaoyangqu/ 推荐查看天气:http://www.362tq.com/chaoyangqu/zuotian.html 推荐查看天气:http://www.362tq.com/chaoyangqu/7tian.html 推荐查看天气:http://www.362tq.com/chaoyangqu/10tian.html 推荐查看天气:http://www.362tq.com/chaoyangqu/15tian.html 推荐查看天气:http://www.362tq.com/chaoyangqu/40tian.html 推荐查看天气:http://www.362tq.com/beijingfengtai/ 推荐查看天气:http://www.362tq.com/beijingfengtai/zuotian.html 推荐查看天气:http://www.362tq.com/beijingfengtai/7tian.html 推荐查看天气:http://www.362tq.com/beijingfengtai/10tian.html 推荐查看天气:http://www.362tq.com/beijingfengtai/15tian.html 推荐查看天气:http://www.362tq.com/beijingfengtai/40tian.html 推荐查看天气:http://www.362tq.com/shijingshan/ 推荐查看天气:http://www.362tq.com/shijingshan/zuotian.html 推荐查看天气:http://www.362tq.com/shijingshan/7tian.html 推荐查看天气:http://www.362tq.com/shijingshan/10tian.html 推荐查看天气:http://www.362tq.com/shijingshan/15tian.html 推荐查看天气:http://www.362tq.com/shijingshan/40tian.html 推荐查看天气:http://www.362tq.com/haidian/ 推荐查看天气:http://www.362tq.com/haidian/zuotian.html 推荐查看天气:http://www.362tq.com/haidian/7tian.html 推荐查看天气:http://www.362tq.com/haidian/10tian.html 推荐查看天气:http://www.362tq.com/haidian/15tian.html 推荐查看天气:http://www.362tq.com/haidian/40tian.html 推荐查看天气:http://www.362tq.com/mentougou/改**|`sed -i` 直接覆盖原文件,建议先备份,或改用 `sed -i.bak` 保留 `.bak` 备份| |**替换结果**|`/images/fa/icon.png` → `/faicon.png`,确认这是你期望的结果| |**空文件风险**|如果 `fgrep` 没找到任何文件,`xargs` 会把空参数传给 `sed`,可能报错| |**建议先预览**|先跑一遍 `fgrep -rl '/images/fa' .` 看看会命中哪些文件|