开发者

grep replacement with extensive regular expression implementation

开发者 https://www.devze.com 2022-12-19 00:09 出处:网络
I have been using grepWin for general searching of files, and wingrep when I want to do replacements or what-have-you.

I have been using grepWin for general searching of files, and wingrep when I want to do replacements or what-have-you.

GrepWin has an extensive implementation of regular expressions, however doesn't do replacements (as mentioned above).

Wingrep does replacements, however has a severely limited range of regular expression implementation.

Does anyone know开发者_运维百科 of any (preferably free) grep tools for windows that does replacement AND has a reasonable implementation of regular expressions?

Thanks in advance.


I think perl at the command line is the answer you are looking for. Widely portable, powerful regex support.

Let's say that you have the following file:

foo
bar
baz
quux

you can use

perl -pne 's/quux/splat!/' -i /tmp/foo

to produce

foo
bar
baz
splat!

The magic is in Perl's command line switches:

  • -e: execute the next argument as a perl command.
  • -n: execute the command on every line
  • -p: print the results of the command, without issuing an explicit 'print' statement.
  • -i: make substitutions in place. overwrite the document with the output of your command... use with caution.


I use Cygwin quite a lot for this sort of task.

Unfortunately it has the world's most unintuitive installer, but once it's installed correctly it's very usable... well apart from a few minor issues with copy and paste and the odd issue with line-endings.

The good thing is that all the tools work like on a real GNU system, so if you're already familiar with Linux or similar, you don't have to learn anything new (apart from how to use that crazy installer).

Overall I think the advantages make up for the few usability issues.


If you are on Windows, you can use vbscript (requires no downloads). It comes with regex. eg change "one" to "ONE"

Set objFS=CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objArgs = WScript.Arguments
strFile = objArgs(0)
Set objFile = objFS.OpenTextFile(strFile)
strFileContents = objFile.ReadAll
Set objRE = New RegExp
objRE.Global     = True
objRE.IgnoreCase = False
objRE.Pattern = "one"
strFileContents = objRE.Replace(strFileContents,"ONE") 'simple replacement
WScript.Echo strFileContents

output

C:\test>type file
one
two one two
three

C:\test>cscript //nologo test.vbs file
ONE
two ONE two
three

You can read up vbscript doc to learn more on using regex

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号