zoukankan      html  css  js  c++  java
  • Grep/Sed的扩展正则表达式开关,以及利用正则表达式中的分组功能

    以一个例子来说明。比如要把代码中的close调用,替换成abcclose。写了一个脚本,有了一些收获。脚本如下:
    #!/bin/bash
    case "$#" in
    0)
        echo 
    "Usage: ./grepclose.sh <path>"
        exit ;;
    1)
        echo 
    "Got path: $1, start working..." ;;
    *)
        echo 
    "Too many arguments. Usage: ./grepclose.sh <path>"
        exit ;;
    esac

    for srcfile in $(find "$1" -name "*.[hc]")
    do
        grep 
    --"[ =({;?:\t]+close[ \t]*\(" -"^close[ \t]*\(" "$srcfile" >& /dev/null
        
    if [ $? -eq 0 ]; then
            echo 
    "Patching file $srcfile"
            cp 
    "$srcfile" "${srcfile}.fdorig"
            sed 
    -"s/^close[ \t]*(/abcclose(/g" "$srcfile"
            sed 
    --"s@([ =({;?:\t]+)close[ \t]*\(@\1abcclose\(@g" "$srcfile"
        fi
    done
     

    1. 使用grep -E来打开grep的扩展正则表达式的功能。所谓扩展,就是像+, ()这样的元字符才能使用。sed使用-r来打开扩展正则表达式。打开了扩展之后,如果要表示一个常量的+, (),就需要用\来转义了。

    2. grep -e可以用来表示多个匹配pattern
    3. 最后一句sed的时候,使用了正则表达式中的分组功能,也就是将[ =({;?:\t]+这个部分定义成一个组,然后在后面就可以用\1来引用(注意\0已经被默认分配成整个pattern)。如果定义了第二个组,那么就用\2来引用。这个很有用,因为在替换的时候,我们不能把close前面的字符删除,所以要保留close前面匹配到的字符,于是分组就特别好用了。
    4. 上述的匹配逻辑是这样的:首先,close顶行头写的,OK;其次,close前面允许有一个或多个空格,等号,小括号,大括号,分号,问号,冒号,tab。其他字符一概不行;最后,close字符串后面允许有0个或者多个空格或tab,然后要有一个小括号。
  • 相关阅读:
    mapx 32位在win8 64位上使用
    ora01940 无法删除当前连接的用户
    powerdesigner操作
    iis7文件夹 首页设置
    安装vs2013以后,链接数据库总是报内存损坏,无法写入的错误
    【ASP.NET】 中 system.math 函数使用
    Android Bundle类
    android intent 跳转
    vs2012 webservice创建
    Linux中的日志分析及管理
  • 原文地址:https://www.cnblogs.com/super119/p/1902033.html
Copyright © 2011-2022 走看看