Wednesday, March 9, 2011

Favorite way to regex a file using perl

Sometimes you want to do some magic fu on your file, while it's not loaded in a vim buffer. This is what I use with perl. I know there is probably a way to do this with sed, but I couldn't find it quickly enough. Most of the time when I do a search and replace out side of vim I want to replace something that's already in the file, with itself in a different position. For example:

I want to replace variablewordspace with variablewordtime, so in the file var.txt I have:

variablewordspace
hammerspace

So what I would do is:


cat var.txt | perl -pe 's/(\w+)space/\1time/'

which would give me the output:


variablewordtime
hammertime



For a brief description:
You are display the file var.txt, through the cat command. Then using the pipe (|) you are passing that to perl, with the switches p and e. Switch e allows you to run from the command line without explicitly writing a perl program, while switch p allows you to run a program against every line on standard input, and prints whatever is in $_ after each line. A search and replace using s/// with the search term in the first set of slashes

/(\w+)space/

The parentheses mark that as a group.

The \w+ means any number of word characters, as where the 'space' just represents the word space.

In the last set of slashes is what you want to replace it with.

/\1time/

\1 represents what is in that first set of parenthesis.

And time of course, represents the letters 'time'

1 comment:

benefactor said...

I'll give you an example of how you can do thig with sed:

sed 's/vim/emacs/g' file

That is all. No need to cat. No need to use perl.