Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sed & grep 批量替换多个文件中的文字 #32

Open
rainyear opened this issue May 21, 2016 · 0 comments
Open

sed & grep 批量替换多个文件中的文字 #32

rainyear opened this issue May 21, 2016 · 0 comments
Assignees

Comments

@rainyear
Copy link
Owner

rainyear commented May 21, 2016

PyTips 文档中的插图开始用的是七牛CDN提供的原始链接,后来绑定了自己的域名之后之前用到的地方都没改,今天想统一改一下,自然想到了用常用的批量查询和修改命令:sed & grep

grep 用于查询包含'7xiijd.com1.z0.glb.clouddn.com' 的所有文件:

grep '7xiijd.com1.z0.glb.clouddn.com' -R ./

qq20160521-0 2x

其中 .ipynb_checkpoints 目录下面的所有文件不需要修改,所以应该忽略掉,man grep 可以查到排除目录的参数是 --exclude-dir ,另外由于结果将用于 sed 进一步修改,因此只希望返回文件名,不需要在文件中的匹配结果:

grep -rl --exclude-dir='.ipynb_checkpoints' '7xiijd.com1.z0.glb.clouddn.com' ./

qq20160521-1 2x

网上搜到一些批量处理的命令不知道是不是抄来抄去还是因为我用的版本不同,sed -i 会报错:

sed: 1: "./Markdowns/2016-03-14- ...": invalid command code .

最后还是自己查一下手册,man sed

 -i extension
         Edit files in-place, saving backups with the specified extension.  If a zero-length extension is given, no backup will be saved.  It is not recom-
         mended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is
         exhausted, etc.

原来 -i 参数用于指定修改文件之后备份文件的后缀名(虽然在 Git 环境下面这样做多虑了,但还是很贴心地怕用户一次修改太多东西没办法撤销),所以正确的指令应该是:

sed -i .bak 's/7xiijd.com1.z0.glb.clouddn.com/qncdn.rainy.im/g' `grep -rl --exclude-dir='.ipynb_checkpoints' '7xiijd.com1.z0.glb.clouddn.com' .`

查看结果:

qq20160521-2 2x

最后删除多余的备份文件:rm Markdowns/*.bak Tips/*.bak

@rainyear rainyear changed the title sed & grep 批量替换多个文件中的文字 sed & grep 批量替换多个文件中的文字 May 21, 2016
@rainyear rainyear self-assigned this Sep 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant