- Problem:
- Take a file full of SQL queries and surround the values in the first paren only with backticks. As the sample queries show, there aren't a set number of values in the query.
- Solution:
- Grab all the values out of the first set of parens, use Perl's split and join to surround each value with backticks, and print out the result.
Sample line: INSERT INTO seen (nick, "when", "where", what) VALUES ('RiSE', '2003-08-03 20:42:04-05', '#foo', 'Part'); INSERT INTO seen (nick, "when", "where", what, something) VALUES ('RiSE', '2003-08-03 20:42:04-05', '#foo', 'Part'); INSERT INTO seen (nick, "when", "where", what, something, else) VALUES ('RiSE', '2003-08-03 20:42:04-05', '#foo', 'Part'); Parser: #!/usr/bin/perl while(<>) { # if the line has has parens then process it, otherwise just print the line out if(/^([^(]+\() # match some number of nonparens, then a paren, # and put it into the variable (.*?) # match anycharacter, but as few as possible, so you # don't go past the very next closing paren. Then put # what you match in variable (\).*$) # match a closing paren, and anything else up to the # end of the line. put it in the variable /x) { $a=$1; # store these temporary variables somewhere $b=$2; $c=$3; $b =~ s/"//g; # strip any quotes (could strip other 'bad' chars here) $b = "`" . # start with an opening backtick join("`, `", # join each item from the array output from the # following split command into a single string, with # each item separated with `, ` split(/,\s*/, $b)) # this split command takes each comma # delimited item and splits it into an # individual string in an array . "`"; # put the closing ` on the string print "$a$b$c\n"; } else { print; } }