User login

Create rewrite rules from new and old URLs using the power of Vim to munge text

As part of the move of Agaric content from Agaric.com to data.agaric.com, we needed to create a bunch (1,592 to be precise) redirects that look like this one:

RewriteRule ^nice-menus-drop-down-bug http://data.agaric.com/node/1048 [NC,R=301,L]

Stefan, in his wizardry, had already pulled a tab-separated-value file of the old path to the new URL, so that what we had was:

nice-menus-drop-down-bug http://data.agaric.com/node/1048

And it needs to look like the above RewriteRule line.

Pulling up the file in a vi editor, consulting a 500 page book on Vim, and then getting help from Stefan, resulted in a command like the below (the colon is just the usual start-of-command symbol).

:%s/^(.)\t(.)$/RewriteRule ^\1 \2 [NC,R=301,L]

In this:

  • the %s specifies that this should be searched and replaced globally
  • the first slash / kicks off the search portion of the command
  • the carrot ^ denotes the beginning of a line
  • the \( and \) are grouping characters (parenthesis) that had to be escaped with the backslash
  • each .* matches any number (the asterisk) of any character (the dot), until the next match
  • the \t matches a tab
  • the second slash / starts the replacement pattern portion of the command
  • RewriteRule ^ is literally that text, as part of the replacement
  • \1 is the result of the first grouped pattern (created by the parenthesis)
  • \2 is the result of the second grouped pattern, that is, whatever was matched by any .* (any number of any characters) between the tab and the end of the line, is inserted here
  • [NC,R=301,L] is more plain text, ending the replacement

So ah, vim, simple. Sort of. But replacing 1592 lines at once was cool.

Searched words: 
surround text with code with vim replace plain text with same string wrapped in specified data

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.