Bash Collection – Script for cutting parts from large file
The following small script was written by me in order to be able to simply cut parts from very large text files.
It is very useful for database administrators to for example cut the SQL statements for creating and restoring one single table from a really large SQL dump.
For this you would need to determine the line numbers from the large file. For the example with restoring a single table from a SQL dump, you would do something like this:
~$ grep -n "CREATE TABLE" ./large.sql.dump
This would give you this example output:
62: CREATE TABLE `table 1`;
256: CREATE TABLE `table 2`;
1532: CREATE TABLE `table 3`;
3245: CREATE TABLE `table 4`;
3643: CREATE TABLE `table 5`;
8436: CREATE TABLE `table 6`;
So, if you now want all the statements for restoring “table 4”, you would need the SQL statements from lines 3245 – 3643.
Since mostly there also is a “DROP TABLE…” one line before the “CREATE TABLE” statement, we would need to substrate at least one line from the last line number.
The line numbers we would need then would be: 3245 – 3642
So, with this information, we then can use the script below. Just type in the command line:
~$ cutter 3245 3642 ./large.sql.dump ./table-4.sql
This command would cut everything from lines 3245 until 3642 (including the given line numbers!) from the original, large dump and put them into a new file “./table-4.sql”.
And here is the script. Just save it as /usr/local/bin/cutter and make it executable (chmod 755 /usr/local/bin/cutter)
Hope it helps.
If you also have some useful scripts, please don’t hesitate to share them with us!
Just contact email@example.com and attach your script with a small description what it does.