命行下的查询与替换字符串

      有时需要在命行下(command-line)的查询与替换字符串,有什么简单高效的方法呢? 首先,如果你在.Net Framework 2.0 version上的话,可以使用PowerShell(实际上Windows后面的操作系统都支持PowerShell). 看下面简单例子:

Get-Content test.txt | ForEach-Object { $_ -replace "2012", "2013" } | Set-Content text2.txt

    上面PowerShell脚本把text.txt文件中所有2012的字符串替换为2013后另存为text2.txt文件,这里使用到PowerShell的管道机制,你可以把上面脚本存为*.ps1文件,在PowerShell控制台就可以执行了.是不是很简单.

第二类方法,不想依赖.Net环境,那可以选择FART这个小工具,下载后是单个fart.exe文件,68.0 KB的32bit程序,有很多功能,看以下参数列表:

Usage: FART [options] [--] <wildcard>[,...] [find_string] [replace_string]

Options:
-h, --help          Show this help message (ignores other options)
-q, --quiet         Suppress output to stdio / stderr
-V, --verbose       Show more information
-r, --recursive     Process sub-folders recursively
-c, --count         Only show filenames, match counts and totals
-i, --ignore-case   Case insensitive text comparison
-v, --invert        Print lines NOT containing the find string
-n, --line-number   Print line number before each line (1-based)
-w, --word          Match whole word (uses C syntax, like grep)
-f, --filename      Find (and replace) filename instead of contents
-B, --binary        Also search (and replace) in binary files (CAUTION)
-C, --c-style       Allow C-style extended characters (\xFF\0\t\n\r\\ etc.)
     --cvs           Skip cvs dirs; execute "cvs edit" before changing files
     --svn           Skip svn dirs
     --remove        Remove all occurences of the find_string
-a, --adapt         Adapt the case of replace_string to found string
-b, --backup        Make a backup of each changed file
-p, --preview       Do not change the files but print the changes

看下面的例子:

     fart.exe -p -r -c -- J:\TEMP\txt\*.tt 2010-2014 2010-2015

执行完上面的命令后,把J:\Temp\txt\文件夹所有扩展为tt的文件,查询2010-2014替换为2010-2015的字符串. 支持预览,通配符,记数等功能.并且fart.exe是一个免费的小程序.

当然实际上还有常见的Bat文件,VBScript等方法来实现但不优雅.希望对您有帮助.
你可能感兴趣的文章:

Powershell实现创建zip压缩文件


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

原文地址:https://www.cnblogs.com/wintersun/p/3085694.html