Perl from command line: substitute regex only once in a file

perl, regex

Solution

A compact way to do this is

perl -i -pe '$done ||= s/old/new/' filename

Problem

I'm trying to replace a line in a configuration file. The problem is I only want to replace only one occurence. Part of the file looks like this. It is the gitolite default config file: ``` # ----------------------------------------------------------------- # suggested locations for site-local gitolite code (see cust.html) # this one is managed directly on the server # LOCAL_CODE => "$ENV{HOME}/local", # or you can use this, which lets you put everything in a subdirectory # called "local" in your gitolite-admin repo. For a SECURITY WARNING # on this, see http://gitolite.com/gitolite/cust.html#pushcode # LOCAL_CODE => "$rc{GL_ADMIN_BASE}/local", # ------------------------------------------------------------------ ``` I would like to set `LOCAL_CODE` to something else from the command line. I thought I might do it in perl to get pcre convenience. I'm new to perl though and can't get it working. I found this: ``` perl -i.bak -p -e’s/old/new/’ filename ``` The problem is -p seems to have it loop over the file line by line, and so a 'o' modifier won't any have effect. However without the -p option it doesn't seem to work...

Original source