views:

3608

answers:

11

I have a ~23000 line sql dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want.

Does anyone know a unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file?

+1  A: 

You could use 'vi' and then the following command:

:16224,16482w!/tmp/some-file

Alternatively:

cat file | head -n 16482 | tail -n 258
Mark Janssen
head -n 16482 file|tail -n 258 should work better
Torsten Marek
And instead of vi you could use ex, that is vi minus interactive console stuff.
Tadeusz A. Kadłubowski
+17  A: 
sed -n 16224,16482p filename > newfile
boxxar
Some explanation would be nice.
furtelwart
+2  A: 
 # print section of file based on line numbers
 sed -n '16224 ,16482p'               # method 1
 sed '16224,16482!d'                 # method 2
Cetra
+1  A: 

perl -ne 'print if 16224..16482' file.txt > new_file.txt

mmaibaum
A: 

Quick and dirty:

head -16428 < file.in | tail -259 > file.out

Probably not the best way to do it but it should work.

BTW: 259 = 16482-16224+1.

jan.vdbergh
+2  A: 

sed -n '16224,16482p' < dump.sql

cubex
A: 

cat file.txt | head -n 16482 | tail -n 258

Does the same but requires and extra process.

amo-ej1
+7  A: 

Quite simple using head/tail:

head -16482 in.sql | tail -258 > out.sql

using sed:

sed -n '16482,16482p' in.sql > out.sql

using awk:

awk 'NR>=10&&NR<=20' in.sql > out.sql
manveru
+11  A: 
sed -n '16224,16482 p' orig-data-file > new-file

Where 16224,16482 are the start line number and end line number, inclusive. This is 1-indexed. -n suppresses echoing the input as output, which you clearly don't want; the numbers indicate the range of lines to make the following command operate on; the command p prints out the relevant lines.

JXG
A: 

cat dump.txt | head -16224 | tail -258

should do the trick. The downside of this approach is that you need to do the arithmetic to determine the argument for tail and to account for whether you want the 'between' to include the ending line or not.

JP Lodine
+1  A: 

I was about to post the head/tail trick, but actually I'd probably just fire up emacs. ;-)

  1. esc-x goto-line ret 16224
  2. mark (ctrl-space)
  3. esc-x goto-line ret 16482
  4. esc-w

open the new output file, ctl-y save

Let's me see what's happening.

sammyo