Using placeholders/variables in a sed command
Posted
by
jesse_galley
on Stack Overflow
See other posts from Stack Overflow
or by jesse_galley
Published on 2012-10-15T15:30:14Z
Indexed on
2012/10/15
15:37 UTC
Read the original article
Hit count: 177
I want to store a specific part of a matched result as a variable to be used for replacement later. I would like to keep this in a one liner instead of finding the variable I need before hand.
when configuring apache, and use mod_rewrite, you can specificy specific parts of patterns to be used as variables,like this:
RewriteRule ^www.example.com/page/(.*)$ http://www.example.com/page.php?page=$1 [R=301,L]
the part of the pattern match that's contained inside the parenthesis is stored as $1 for use later. So if the url was www.example.com/page/home
, it would be replaced with www.example.com/page.php?page=home
. So the "home" part of the match was saved in $1 because it was the part of the pattern inside the parenthesis.
I want something like this functionality with a sed
command, I need to automatically replace many strings in a SQL dump file, to add drop table if exist commands before each create table, but I need to know the table name to do this, so if the dump file contains something like:
...
CREATE TABLE `orders`
...
I need to run something like:
cat dump.sql | sed "s/CREATE TABLE `(.*)`/DROP TABLE IF EXISTS $1\N CREATE TABLE `$1`/g"
to get the result of:
...
DROP TABLE IF EXISTS `orders`
CREATE TABLE `orders`
...
I'm using the mod_rewrite syntax in the sed
command as a logical example of what I'm trying to do.
Any suggestions?
© Stack Overflow or respective owner