14

I have a large file which I am only interested in the first couple of megabytes in the head.

How do I extract the first x-megabyte from a large file in unix/linux and put it into a seperate file?

(I know the split command can split files into many pieces. And using bash scripts I can erase the pieces I don't want. I would prefer a easier way)

peterh
  • 11,875
  • 18
  • 85
  • 108
umps
  • 1,119
  • 4
  • 15
  • 25
  • 1
    [This answer](http://stackoverflow.com/questions/218912/linux-command-like-cat-to-read-a-specified-quantity-of-characters) talks about the same issue. – pareshverma91 Sep 01 '12 at 01:15

4 Answers4

20

Head works with binary files and the syntax is neater than dd.

head -c 2M input.file > output.file

Tail works the same way if you want the end of a file.

Roger Heathcote
  • 3,091
  • 1
  • 33
  • 39
18

E.g.

 dd if=largefile count=6 bs=1M > largefile.6megsonly

The 1M spelling assumes GNU dd. Otherwise, you could do

 dd if=largefile count=$((6*1024)) bs=1024 > largefile.6megsonly

This again assumes bash-style arithmetic evaluation.

peterh
  • 11,875
  • 18
  • 85
  • 108
sehe
  • 374,641
  • 47
  • 450
  • 633
3

On a Mac (Catalina) the head and tail commands don't seem to take modifiers like m (mega) and g (giga) in upper or lower case, but will take a large integer byte count like this one for 50 MB

head -c50000000 inputfile.txt > outputfile.txt
WCBdata
  • 41
  • 3
1

Try the command dd. You can use "man dd" to get main ideas of it.

wakensky
  • 43
  • 1
  • 2