0

Ubuntu 9.10

Hi Guys,

I want to create a script that will automatically update a single line in an .htaccess file. Could someone please point me to some instructions for creating a basic "find and replace" script?

I'm imagining something that basically says "look for special markers #ABC and #XYZ... remove entries between the markers and replace it with 'foo'".

3 Answers 3

7

You want sed: sed -i s/regex to look for/string to replace it with/

If it needs to be multiple lines long, you can write more complicated scripts, although at some point sed's power and brevity does start to work against it, and I prefer to start writing in a more verbose but generally comprehensible scripting language (I prefer Ruby, but tastes vary).

If you provide an actual example of what you're trying to accomplish, someone can probably come up with "the best" way to do it; at the moment your example is a big vague to give a concrete solution.

4
  • when using sed, you can also use a sedscript that contains your commands and call it with -f. Man page: unixhelp.ed.ac.uk/CGI/man-cgi?sed Dec 3, 2009 at 3:08
  • 1
    What's this obsession with linking to random manpage sites on the web instead of just running man sed? Especially when the ones on your system will document whatever you're running, instead of some random version which may or may not be the same or even compatible?
    – womble
    Dec 3, 2009 at 3:28
  • is that not safer than assuming everyone is running on a linux box? Dec 3, 2009 at 20:04
  • Given that you're linking to a GNU sed man page, and it's pretty rare for installation of GNUtilities not to come with man pages, I'd say yeah, it's not safer.
    – womble
    Dec 4, 2009 at 23:24
1

Try this:

awk '/^#ABC/ {start=1; print; next} /^#XYZ/ {start=0; print "foo"; print; next} start!=1 {print}' .htaccess > .htaccess.NEW

It can be shortened to:

awk '/^#ABC/ {start=1; print; next} /^#XYZ/ {start=0; print "foo"} start!=1 {print}' .htaccess > .htaccess.NEW
1

If your files are small (.htaccess should be, methinks), then Perl can "slurp" them up and operate on the whole thing as a single string, using s///s (the 's' modifier at the end treats the whole string as a single line).

Example: perl -i.bak -p -0 -e 's/#ABC\n.*#XYZ/foo/s' list of file names

-i.bak tells perl to save backups, in this case called list.bak of.bak file.bak names.bak -p -0 tells perl to slurp the whole file and -e tells it to apply the regular expression on the command line.

This particular version will only replace the first set of markers, and will do nothing if the markers don't exist at all (but it will still create the backup files).

1
  • This script also replaces markers, don't know if it is the needed functionality.
    – Icapan
    Dec 7, 2009 at 14:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .