1

I have what I thought was a simple problem. I have a mysqldump file occupying several GBs, and I want to create a script that will extract just the lines of the text pertaining to one table (variable passed to the script) and save those to a new file.

The section I want to extract always starts with:

-- Table structure for table `myTable`

And always ends with:

UNLOCK TABLES;

Where the table name and the number of lines I want afterward are variable. I'm able to find the start of the section with:

START=$(grep -n "Table structure for table \`$2\`" "$1" | awk -F ":" '{print $1}')

Where $1 is the file to search and $2 is the table name. This works just fine, but then I'm stuck. I know I can extract the lines with sed once I have the ending line number, but finding that ending line number is the tricky part.

I need to find the line number of the first occurrence of UNLOCK TABLES; after my $START line number, and I'm lost on how to do that.

For more detail, here's an example of one section of text I would want to extract:

--
-- Table structure for table `myTable`
--

DROP TABLE IF EXISTS `myTable`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `myTable` (
  `column1` varchar(12) NOT NULL,
  `column2` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`column1`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `myTable`
--

LOCK TABLES `myTable` WRITE;
/*!40000 ALTER TABLE `myTable` DISABLE KEYS */;
INSERT INTO `myTable` VALUES ('test11', 'test12'),('test21', 'test22');
/*!40000 ALTER TABLE `myTable` ENABLE KEYS */;
UNLOCK TABLES;

Thanks in advance.

1 Answer 1

3

Use sed; you don't need to worry about explicit line numbers; you can just select the range using regexes for both the first and last line.

firstLine="-- Table structure for table \`$2\`"
secondLine="UNLOCK TABLES;"

sed -n "/$firstLine/,/$secondLine/p" "$1"

The -n limits sed to printing only those lines that match the desired range.

Sign up to request clarification or add additional context in comments.

1 Comment

So this will find the first occurrence of $secondLine after $firstLine?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.