find - replace

最后更新:2012-04-24, Ver 2.1.7.0424

 

简介

fr - 在文件中批量查找并替换匹配的字符串
  • 支持一次性指定多个文件通配符和文件列表。
  • 支持管道模式,与其它命令协同工作;支持半管道模式,从文件中获取输入,但将结果写到标准输出。
  • 支持包含子目录。
  • 支持普通匹配、正则匹配、可忽略大小写、可跨行匹配。替换时可以使用正则的子表达式。
  • 支持 TCL 8.2 兼容的高级正则表达式(ARE)。
  • 同时支持 posix 标准的扩展正则表达式及 perl 风格的正则匹配。
  • 支持 url encoding (percent-encoding, rfc 3986) 风格的换码序列。
  • 可以格式化替换内容为全大写或全小写,便于在批处理中对环境变量和命令行参数做大小写一致化处理。
  • 支持 DOS(Windows)、Macintosh 和 unix 风格的换行符,可选择自动识别(默认)或手动指定。
  • 统计功能,列出每个文件中的替换次数、总替换次数等。
  • 支持 Win32 和纯 DOS 环境(纯DOS环境中需要 HX DOS Extender 支持)。
  • 支持 POSIX 环境,提供 linux x86/x64、FreeBSD、NetBSD、Solaris 等版本下载。

 

更新历史

2012-04-24, Ver 2.1.7.0424

NEW: 新增 -ue 参数,支持 url encoding (percent-encoding, rfc 3986) 风格的换码序列。

2009-12-13, Ver 2.1.6.1213

NEW: 新增 -errstop 参数。使用此参数时,遇到无法访问的文件和子目录会报错并自动终止查找。不使用此参数时,fr 会自动跳过无法访问的子目录。对于无法读写的文件,fr 会输出一行报错信息,但不会终止搜索。

2009-03-12, Ver 2.1.5.0312

FIX: 修正了在使用 /r 或 /ric 参数并且使用 ARE 'p' 和 's' 模式进行匹配时,'^' 有时仍然会匹配行首的问题。
     例如:在 dos 格式的文件中,/r:"***:(?p)(^.*)\n" 会匹配所有行,而不仅仅是文件的第一行。
UPD: 现在 -exp 默认为开启状态,要禁用此选项,需要指定 -noexp 开关。

2008-09-09, Ver 2.1.4.0909

UPD: 增强了正则行首锚点 '^' 的适应性。

2008-09-08, Ver 2.1.3.0908

FIX: 纠正了正则表达式零长匹配时会出现无限循环的问题(例如,在内容“aaa.bbb”中将“[^.]*”替换为“z”)。
FIX: 纠正了正则行首锚点解析不正确的问题(例如,在内容“ccc”将“^c”替换为“z”)。

2008-08-16 Ver 2.1.2.1126

新增高级正则表达式(ARE)支持

2007-01-20 Ver 2.1.1.120

新增 -exp 选项,开启该选项后,程序的内存使用量将增加一倍,但是在很多情况下,其处理速度将得到极大改善。碰到性能问题的弟兄们可以试试。

该算法使用额外的内存消除了原地替换时带来的内存抖动,所以文件中要替换的值越多,算法带来的性能提升就越明显。在 siwen@CCF 兄提供给我的样本上测试,开启了 -exp 选项以后,fr 完成任务的时间从 1小时 降低到 1.5 秒(文件体积 8.5MB,文件中需要替换的项目为 25 万项)。

 

典型应用

  • 在命令行中单独使用,或作为管道过滤器使用。例如:“unzip -l *.zip | fr /r:"^(.{22}:\d\d\s*|(A| \a| -|.*files$).*\n)" /t”将当前目录下的所有zip文件中的文件干净地列出,同时过滤标题行、统计行以及每行的文件大小、修改时间等内容。
     
  • 在批处理中应用。批处理片断:fr *.lst -fic:NewDir -tu:"%1" 将当前目录下所有 .lst 文件中的 newdir 替换为第一个命令行参数(全大写)。

    另一个简单的例子:将“@fr kog-Swd5b.sfv /r:"^(.*) (\x\x)(\x\x)(\x\x)(\x\x)$" /t:"\5\4\3\2 *\1"”保存为批处理文件“sfv2hash.bat”,在下载任何带有 sfv 校验信息的文件后,可以使用 sfv2hash check.sfv 将其转换为标准 hash 信息格式。然后就可以使用 crypto v check.sfv /halgm:crc32 或其它散列验证工具进行文件验证。
     
  • 与其它工具配合使用。

 

简单中文帮助

C:\Documents and Settings\Administrator>
#fr

===============================================================================
      find and replace Ver 2.1.7.0424 by BaiYang / 2004 - 2012, 免费软件
                        主页地址 - http://baiy.cn
===============================================================================
在文件和管道中寻找字符串,并将它们替换为其它内容

用法: fr [文件通配符1 文件通配符2 ...] {查找选项:查找内容} {替换选项:替换为} 
         [其它选项]

===============================================================================
查找选项:
  -f:      - 匹配精确串
  -fic:    - 匹配精确串(忽略大小写)
  -r:      - 正则表达式匹配
  -ric:    - 正则表达式匹配(忽略大小写)
  -rnnl:   - 跨行正则匹配
  -rnnlic: - 跨行正则匹配(忽略大小写)

===============================================================================
替换选项:
  -t:      - 将匹配的内容替换为指定字符串
  -tu:     - 先将指定的“替换为”字符串变为大写,然后开始替换
  -tl:     - 先将指定的“替换为”字符串变为小写,然后开始替换
  注意: 如果您正在使用正则匹配,那么您可以在“替换为”字符串中使用子表达式代换 
        (\0 ~ \9)

===============================================================================
其它选项:
  -h -?    - 当前屏幕
  -s       - 包含子目录
  -exp     - 启用内存扩展算法,将会加倍 fr 的内存使用量,但是很多时候可以极大地
             提高执行效率。现已默认开启。
  -noexp   - 禁用内存扩展算法,参考:-exp 选项的说明。
  -stdin   - 从标准输入设备获得要查找的内容,并将结果从到标准输出设备(如果未指
             定任何文件模板的话,则自动启用该选项)
  -stdout  - 像平时一样, 从文件中获得输入, 但将结果送到标准输出(而不是写回文
             件)
  -frc     - 显示每个文件内发生的替换次数
  -trc     - 显示所有文件总共发生的替换次数
  -errstop - 当遇到文件或子目录访问错误时,终止搜索任务。
             默认: 遇到无法访问的子目录访跳过;遇到无法访问的文件时,打印错误信
             息并继续
  -ue      - 为所有查找和替换选项应用 url encoding (percent-encoding, rfc 3986)
             格式为:'pct-encoded = "%" HEXDIG HEXDIG'

===============================================================================
POSIX 和 Perl 风格的正则表达式:

  - "find - replace" 完整支持 POSIX.2 扩展标准及 Perl 风格的正则表达式。
    以下是支持的字符类及其对应关系:
       POSIX           perl       描述
       --------------------------------------------------------------------
       [:alnum:]                  字母和数字
       [:alpha:]       \a         字母
       [:lower:]       \l         小写字母
       [:upper:]       \u         大写字母
       [:blank:]                  空格和制表符
       [:space:]       \s         空白字符
       [:cntrl:]                  控制字符
       [:digit:]       \d         十进制数字
       [:xdigit:]      \x         十六进制数字
       [:graph:]                  可打印字符(不包括空白符)
       [:print:]       \p         可打印字符(包括空白符)
       [:punct:]                  标点符号

  - 以下是一些 perl 的特殊字符类:
       perl   POSIX等效         描述
       --------------------------------------------------------------------
       \o     [0-7]             八进制数字
       \O     [^0-7]            非八进制数字
       \w     [[:alnum:]_]      单词组成
       \W     [^[:alnum:]_]     非单词组成
       \A     [^[:alpha:]]      非字母 
       \L     [^[:lower:]]      非小写字母
       \U     [^[:upper:]]      非大写字母
       \S     [^[:space:]]      非空白符
       \D     [^[:digit:]]      非十进制数字
       \X     [^[:xdigit:]]     非十六进制数字
       \P     [^[:print:]]      非可打印字符
       \<     [^[:alpha:]_]     单词开始
       \>     [^[:alnum:]_]     单词结束

  - 注意: posix 字符类是必须工作在集合中的(“[”和“]”内)。相反,perl 风格
          的字符类是工作在集合运算之外的。

  - 此外,为了便于在命令行输入一些特殊字符,特别定义了一下别名:
       perl风格      POSIX风格       描述
       -----------------------------------------------------------------------
       \"            [:dq:]          双引号
       \'            [:sq:]          单引号
       \t            [:tb:]          制表符
       \n            [:nl:]          换行符 (0x0A)
       \r            [:rt:]          回车符 (0x0D)
       \b            [:bs:]          退格符

===============================================================================
TCL 8.2 兼容的高级正则表达式(ARE)

  - 为 -r:, -ric:, -rnnl:, -rnnlic:  等命令添加 '***:' 前缀即可开启高级正则表达
    式功能。ARE 提供了比 POSIX ERE/BRE 更为强大的正则匹配语法,并且使用一套自定
    义的字符类。有关 ARE 的详细信息,请访问:
    http://baiy.cn/utils/_regex_doc/index.htm

===============================================================================
开关的前缀和后缀:
  * 所有命令行开关(选项)都是大小写无关的(如: "-fic:" 和 "-FIC:")
  * 开关的前缀可以是 "-" 或 "/"(如: "/s" 和 "-s")
  * 开关的后缀可以是 ":" 或 "="(如: "/f:", "/f=", "-f:" 和 "-f=" 等效)

===============================================================================
应用示例:
  fr *.txt *.htm -f:teh -t:the
  fr *.txt -fic:"My Dir" -tu:"%ROOTDIR%"
  fr *.cpp *.h -r:"***:(#define.*?)MY_DEF" /t:"\1HER_DEF"
  fr *.txt -f:"abc%10%1A" -t:"def%00%1F" -ue
  type server.log | fr /r:"Connected.*218.79" /t:"**Attack** \0"
  type server.log | fr /r:"^(Smith|James).*\n" /t
  unzip -l *.zip | fr /r:"^(.{22}:\d\d\s*|(A|  \a| -|.*files$).*\n)" /t

 

帮助屏幕

D:\product\find_replace\Release>
#fr

===============================================================================
      find and replace Ver 2.1.7.0424 by BaiYang / 2004 - 2012, Freeware
                          homepage - http://baiy.cn
===============================================================================
Find string in files or pipe, and replace it to another string

USAGE: fr [filePattern1 filePattern2 ...] {FindOption:StringToFind}
          {ReplaceOption:StringToReplacement} [OtherOptions]

===============================================================================
FIND OPTIONs:
  -f:      - find
  -fic:    - find ignore case
  -r:      - regular expresion find
  -ric:    - regular expresion find ignore case
  -rnnl:   - regular expresion find ignore newline
  -rnnlic: - regular expresion find ignore newline ignore case

===============================================================================
REPLACE OPTIONs:
  -t:      - change the match to"StringToReplacement"
  -tu:     - make the "StringToReplacement" upper case, and change the match
             to it.
  -tl:     - make the "StringToReplacement" lower case, and change the match
             to it.
  NOTE: If find option you specified is a regular expresion method, the replace
        option will support sub expressions (\0-\9) as well.

===============================================================================
OTHER OPTIONs:
  -h -?    - Is screen
  -s       - include sub folders
  -exp     - enable the memory expand algorithm, will double the memory usage,
             but MUCH quick in many case. Now Default.
  -noexp   - disable the memory expansion algorithm. see also: -exp.
  -stdio   - get input from standard input device (keyboard and pipe),
             and put the results to standard output device.
             default when file pattern is omitted.
  -stdout  - get input from file(s) as normally, but put the results to
             standard output device.
  -frc     - show File Replacements Count
  -trc     - show Total Replacements Count
  -errstop - stop on a file or sub-directory access error (the old behave).
             DEFAULT: ignore the access error and try to continue.
  -ue      - apply url encoding (percent-encoding, rfc 3986) for all find and
             replacement options. 'pct-encoded = "%" HEXDIG HEXDIG'

===============================================================================
POSIX and perl style Regular Expression:

  - "find - replace" fully support POSIX.2 Extended and Perl style Regular
     Expresion. Here is a list of they character classes:
       POSIX           perl       Description
       --------------------------------------------------------------------
       [:alnum:]                  letters and digits
       [:alpha:]       \a         letters
       [:lower:]       \l         lowercase letters
       [:upper:]       \u         uppercase letters
       [:blank:]                  space and tab characters
       [:space:]       \s         whitespace characters
       [:cntrl:]                  control characters
       [:digit:]       \d         decimal digits
       [:xdigit:]      \x         hexadecimal digits
       [:graph:]                  printable characters excluding space
       [:print:]       \p         printable characters including space
       [:punct:]                  punctuation characters

  - And here a some special char classes in perl:
       perl   POSIX equivalent  Description
       --------------------------------------------------------------------
       \o     [0-7]             octal digit
       \O     [^0-7]            non-octal digit
       \w     [[:alnum:]_]      word character
       \W     [^[:alnum:]_]     non-word character
       \A     [^[:alpha:]]      non-alphabetic character
       \L     [^[:lower:]]      non-lowercase character
       \U     [^[:upper:]]      non-uppercase character
       \S     [^[:space:]]      non-whitespace character
       \D     [^[:digit:]]      non-digit
       \X     [^[:xdigit:]]     non-hex digit
       \P     [^[:print:]]      non-printable characters
       \<     [^[:alpha:]_]     begin of word
       \>     [^[:alnum:]_]     end of word

  - note: posix char class must working in the square brackets. contrary,
          perl's must stay outside of the brackets.

  - And several alias has been created to help input some special char:
       perl style    POSIX style     Description
       -----------------------------------------------------------------------
       \"            [:dq:]          double quotation
       \'            [:sq:]          single quotation
       \t            [:tb:]          table
       \n            [:nl:]          new line (0x0A)
       \r            [:rt:]          return (0x0D)
       \b            [:bs:]          backspace

    NOTE: the posix style alias also available on /t, /tu and /tl when using
          the regex ("/r" and "/ric") match.

===============================================================================
TCL 8.2 Compatibal ARE expression:

  - Use '***:' prefix with -r:, -ric:, -rnnl: or -rnnlic: to enable Advanced
    Regular Expression mode. The ARE mode have more powerful expression then
    POSIX BRE and ERE rule. And it has it's own char classes. More info at:
    http://baiy.cn/utils/_regex_doc/index.htm

===============================================================================
SWITCH PREFIX and SUFFIX:
  * All switchs (options) are case-insensitive (i.e: "-fic:" or "-FIC:")
  * Switch Prefix can be either "-" or "/" (i.e: "/s" or "-s")
  * Switch Suffix can be either ":" or "=" (i.e: "/f:", "/f=", "-f:" or "-f=")

===============================================================================
EXAMPLEs:
  fr *.txt *.htm -f:teh -t:the
  fr *.txt -fic:"My Dir" -tu:"%ROOTDIR%"
  fr *.cpp *.h -r:"***:(#define.*?)MY_DEF" /t:"\1HER_DEF"
  fr *.txt -f:"abc%10%1A" -t:"def%00%1F" -ue
  type server.log | fr /r:"Connected.*218.79" /t:"**Attack** \0"
  type server.log | fr /r:"^(Smith|James).*\n" /t
  unzip -l *.zip | fr /r:"^(.{22}:\d\d\s*|(A|  \a| -|.*files$).*\n)" /t

 

POSIX 版本说明

安装步骤:
  1. 下载 fr_xxx_yyy.zip (其中 xxx 为操作系统,yyy 为硬件平台)。
  2. 使用 upzip 命令解压:'unzip fr_xxx_yyy.zip'。
  3. 复制:'cp fr /bin'

注意事项:

  • 不同于 Windows/DOS 平台,由于 '/' 为 posix 路径分割符,所以开关前缀只能使用 '-',例如:'-f:1234' 等。
  • 由于 posix shell 自动展开文件通配符,这将导致匹配子目录功能不正常,所以应当使用单引号或双引号引用文件模板,例如:fr '/etc/*' -s -r:"(192.168.)155.(\d+)" -t:"\1145\2" 等。

 

下载

fr.rar             (Windows/DOS,DOS 版需要 HXDOS 环境支持)
fr_linux_x86.zip   (在 Ubuntu 8.04 上测试通过)
fr_linux_x64.zip   (在 Ubuntu 8.04 上测试通过)
fr_freebsd_x64.zip (在 FreeBSD 7.0 上测试通过)
fr_netbsd_x86.zip  (在 NetBSD 5.0.1 上测试通过)
fr_solaris_x86.zip(在 OpenSolaris 2009.06 上测试通过)