exec命令

linux专用实例

* 在当前目录下(包含子目录),查找所有txt文件并找出含有字符串"bin"的行::

    find ./ -name "*.txt" -exec grep "bin" {} \;

* 在当前目录下(包含子目录),删除所有txt文件::

    find ./ -name "*.txt" -exec rm {} \;

* 把目录folder下(包含子目录)的html文件打包::

    find <folder>/ -name "*.html" -type f -exec tar zcvf <abc>.tar.gz {} \;

* 把目录folder下(包含子目录)的html文件拷贝到文件夹folder2中::

    find <folder>/ -name "*.html" -type f -exec cp {} <folder2>/ \;

Mac专用实例

Mac下与 linux 的不同点-替换相关功能:

// 可以在-i 参数后增加字符串把原来文件备份,如:
$ sed -i "recordTxt"

会在修改的文件后面加上recordTxt
// 如: 修改 mysql.txt 会增加 mysql.txtrecordTxt

find . -type f -exec sed -i "recordTxt"  's/<before>/<replace>/g' {} \;

如果不想备份,直接修改,则使用 sed -i ""

find . type f -exec sed -i "" 's/<before>/<replace>/g' {} \;

实战

  1. 把查到的文件中的class前面都加个回车:

    $ find . type f -exec sed -i 's/class/\'$'\nclass/g' {} \;
    // \n改为\'$'\n代替回车
    
  2. 把当前目录下(包含子目录)的文件中的 ($session[0]['id'] 修改为 ($session[0]['user_id']:

    $ find . -type f -exec sed -i "s/(\$session\[0]\['id']/(\$session\[0]\['user_id']/g" {} \;
    
  3. 不使用默认分隔符 \ 改为 |:

    $ find . -type f -exec sed -i "" 's|](/from/|](/to/|g' {} \;
     说明: 为解决查询和替换文本中有默认分隔符问题
    

实战-rst 转 md

‘.. note:: <content>’ 替换成 ‘`note\n<content>\n`’:

find . -type f -name "*.rst" -exec perl -0777 -pi -e 's/\.\. note::(\s+.*?)(?=\n\n|\n\S|\n$)/```note\n$1\n```/gs' {} \;

“.. figure:: <pic url>” 替换为 “![](<pic_url>”:

find . -type f -name "*.rst" -exec perl -pi -e 's/\.\. figure:: ([^\s]+)/![]($1)/g' {} \;

“::n<content>” 转为 `\n<content>\n`:

find . -type f -name "*.rst" -exec perl -0777 -pi -e 's/(^|\n)::\n\n(\s+.*?)(?=\n\n|\n[^\s]|\n$)/\n```\n$2\n```/gs' {} \;

将 rst 格式的标题转换为 markdown 格式:

find . -type f -name "*.md" -exec perl -0777 -pi -e '
    s/^(.+)\n=+$/## $1/gm;
    s/^(.+)\n-+$/### $1/gm;
    s/^(.+)\n^+$/#### $1/gm;
' {} \;