FreeBSD/Linux 下各种查找替换字符串的办法

在Freebsd下我们常常要进行字符串的查找替换,有在vim编辑器里面进行的,也有在shell下进行的,这样的事情常遇到,但是每次都会感到有些概念模糊,尤其对类似awk、sed、grep、find等命令的具体参数使用问题上老是糊涂,下面收集几个常用的方法,实在不能理解就死记算了!

1、在vi中使用的查找替换方法
利用 :s 命令可以实现字符串的替换。具体的用法包括:
:s/str1/str2/ 用字符串 str2 替换行中首次出现的字符串 str1
:s/str1/str2/g 用字符串 str2 替换行中所有出现的字符串 str1
:.,$ s/str1/str2/g 用字符串 str2 替换正文当前行到末尾所有出现的字符串 str1
:1,$ s/str1/str2/g 用字符串 str2 替换正文中所有出现的字符串 str1
:g/str1/s//str2/g 功能同上从上述替换命令可以看到:g 放在命令末尾,表示对搜索字符串的每次出现进行替换;不加 g,表示只对搜索字符串的首次出现进行替换;g 放在命令开头,表示对正文中所有包含搜索字符串的行进行替换操作。

2、在shell中使用find结合grep进行文件的替换
# find ./ -exec grep str1 ‘{}’ \; -exec sed -i.bak s/str1/str2/g ‘{}’ \;
上面命令可以在当前目录下(包括子目录)查找包含str1的文件,自动替换成str2,并且生成源文件的bak文件

更多方法正在不断收集更新中。。。

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
One Response
  1. dyfire says:

    很实用的东西~:)  谢谢 大哥
    是否可以转载过去

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image