1

I want to perform complex find and replace that I do with notepad++ using command line. I found many solutions from web but none of them matches my requirements.

I have one file in which I want to perform regex find and replace

An another file containing regex strings (both find with and replace with. I can play with that to make two separate files or anything.)

Please also guide how to place regex find and replace strings in this file if it is possible to do above task.

Edit

Any PCRE compatible find and replace utility for windows?

Rahul Patel
  • 223
  • 4
  • 11

1 Answers1

1

there is the windows "findstr" command, but it can't replace and has limited regex support. Beyond that look to how to do it with *nix, and then use those tools in windows. So you can get grep and sed for windows.

Some batch people may use a tool (perhaps authored by batch expert dave benham) that merges microsoft jscript with batch and has options for search and replace. I guess that's perfect if you're on a very locked down system and can't even download an EXE. But otherwise downloading or copy/pasting a script is almost like getting a third party thing and then there are already tools out there like grep and sed that are widely used and can be downloaded for windows.

The *? is lazy evaluation, which is a bit advanced and needs -P (PCRE - perl compatible regular expressions)

C:\>echo abccccdd| grep -oP "a.*?c"
abc

C:\>

You can remove the -P if you want, if the regex is less advanced. Though I keep it.

Sed doesn't go as far as PCRE, but does support what seems to be the next best thing with these command line utilities. ERE (extended regular expressions). Using sed with -r can save you from having to use superfluous backslashes. Last time I checked, without -r it uses BRE(basic regular expressions).

This means replace that regex match with nothing

C:\>echo abccccdd| sed -r "s/c{2,3}//"
abcdd

This /g modifier, will do a global search and replace so won't just replace the first match

C:\>echo abacacda| sed "s/a//g"
bccd

You can get it with gnuwin32, or you can use it from cygwin though then use single quotes and if using cygwin's then better to do it from cygwin's shell e.g. cygwin's bash shell.

These command can operate on files obviously.

C:\>type a.a
asdf

C:\>


C:\>grep -o a a.a
a

C:\>sed "s/a/z/" a.a
zsdf

C:\>

Or Perl

grep won't search and replace. Sed will, though sed doesn't support PCRE(at least not the sed I have). Another option is perl. Perl Regexes are as good as PCRE if not better. Look here https://stackoverflow.com/questions/4794145/perl-one-liner-like-grep and see it mentions this link Perl for matching with regular expressions in Terminal? see my answer there it has perl forms of grep and sed, and you'll have great regex support with perl obviously

If you view my answer at that second link (as I said), then you'll see I say that I got and used perl there in cygwin, as well as how it can be used.

barlop
  • 25,198