10

I am running centos and I have around 1,300 files in a folder that each need to be bzipped individually. What would be the easiest way of handing this?

Steven Kull
  • 141
  • 1
  • 2
  • 7

5 Answers5

24

If all the files are in a single directory then:

bzip2 *

Is enough. A more robust approach is:

find . -type f -exec bzip2 {} +

Which will compress every file in the current directory and its sub-directories, and will work even if you have tens of thousands of files (using * will break if there are too many files in the directory).

If your computer has multiple cores, then you can improve this further by compressing multiple files at once. For example, if you would like to compress 4 files concurrently, use:

find . -type f -print0 | xargs -0 -n1 -P4 bzip2
sagi
  • 5,619
  • 1
  • 30
  • 31
  • I don't understand where in your last command you specify to use bzip2 – Herman Toothrot Jun 06 '16 at 15:03
  • 2
    What is the meaning of `{} +`? – wsdzbm Feb 14 '17 at 00:29
  • 2
    There is a very good answer to Lee's question/comment here: [https://unix.stackexchange.com/questions/12902/how-to-run-find-exec](https://unix.stackexchange.com/questions/12902/how-to-run-find-exec) – Logan Sep 16 '19 at 16:47
  • For anyone curious on applying this to decompression, it's enough to simply pass in that option: `find . -type f -print0 | xargs -0 -n1 -P4 bzip2 -d` – Scott McAllister May 24 '21 at 13:52
3

To bzip2 on a multi-core Mac, you can issue the following command (when you're inside the folder you want to bzip)

find . -type f -print0 | xargs -0 -n1 -P14 /opt/local/bin/bzip2

This will bzip every file recursively inside the folder your terminal is in using 14 CPU cores simultaneously.

You can adjust how many cores to use by editing

 -P14

If you don't know where the bzip2 binary is, you can issue the following command to figure it out

which bzip2

The output of that command is what you can replace

/opt/local/bin/bzip2

with

Shaheen Ghiassy
  • 7,397
  • 3
  • 40
  • 40
1

I have written below script to bzip2 files to another directory

#!/bin/bash
filedir=/home/vikrant_singh_rana/test/*

for filename in $filedir; do
name=$(basename "$filename" | sed -e 's/\.[^.]*$//')
bzip2 -dc $filename > /home/vikrant_singh_rana/unzipfiles/$name
done

my sample file name was like

2001_xyz_30Sep2020_1400-30Sep2020_1500.csv.bz2

I was not able to get any direct command, hence made this. This is working fine as expected.

vikrant rana
  • 4,509
  • 6
  • 32
  • 72
0

From inside the directory: bzip2 *

Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
0
find PATH_TO_FOLDER -maxdepth 1 -type f -exec bzip2 -zk {} \;