Search code examples
bashunixzshbz2

How can I get the 10 first lines of all my compressed files?


I have a bunch of M files, from which I want to extract the first N lines (from each). My files are compressed in BZ2. Otherwise, doing head -10 * would be enough.

Ex: Assume I want to extract the 2 first lines from all my files (A.txt, B.txt, C.txt underneath).

A.txt:

1A
2A
3A
4A

B.txt:

1B

C.txt:

1C
2C

The expected result should be something like that (ie containing these lines, not forced to be in order):

1A
2A
1B
1C
2C

I tried the following:

  • bzcat * | head -10 gives me the first 10 lines of the whole decompressed bunch of files, ie not enough output. I would have only 1A 2A here.
  • bzcat | head -10 * gives me the first 10 lines of each compressed file, ie it's impossible to read.

Does anyone have an idea?


Solution

  • Use a for loop:

    for i in *; do bzcat "$i" | head -n10; done
    

    or find:

    find -type f -exec bash -c 'bzcat $1 | head -n10' _ {} \;