Search code examples
powershellcmdcommand-linegit-bash

windows cmd to copy the text between two points in a .sql file and write to another .sql File


There is this mySQL dump file(file.sql) with the table structures and insert statements for a database.

--DO NOT COPY
--DO NOT COPY
-- Table structure for table `address`
--

DROP TABLE IF EXISTS `address`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `address` (
`ENCODEDKEY` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`ADDRESSTYPE` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT 
NULL,
`CITY` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `address`
--

 LOCK TABLES `address` WRITE;
/*!40000 ALTER TABLE `address` DISABLE KEYS */;
INSERT INTO `address` VALUES ( 'ENCODEDKEY','ADDRESSTYPE','CITY');
/*!40000 ALTER TABLE `address` ENABLE KEYS */;
UNLOCK TABLES;
--DO NOT COPY
--DO NOT COPY

I want to copy the text from this file.sql between two points which is a starting point to a ending point.

The starting point should be the exact string of =

Table structure for table 'find_tablename'

The ending point should be exact string of =

UNLOCK TABLES;

And I want to copy/read all the text between those 2 points and write to a new .sql file

This Unix command using SED does the task:

sed -n -e '/-- Table structure for table `address`/,/UNLOCK TABLES/p' file.sql > new_file.sql

However i am looking for the windows equivalent using the command line(cmd). I started to do this with the @type command but I need some sort of IF statement to tell the process to only copy all the text between those 2 points and write to a new .sql file.

@type C:\Users\Documents\file.sql > C:\Users\Documents\new_file.sql

Solution

  • I don't think there is a command for this specific case. And I hope you're not going to try this in cmd.exe.

    In PowerShell, you could do this:

    $write = $false
    $(switch -CaseSensitive -File ("file.sql") {
        '-- Table structure for table `address`' { $write = $true; $_ }
        'UNLOCK TABLES;' { if ($write) { $_; break; } }
        default { if ($write) { $_ }}
    }) | Set-Content "new_file.sql"
    

    If you need something like this more often, you could write your own function for it.