高度な unzip オプション
これまでに ZIP ファイルの抽出の基本をマスターしたので、様々なシナリオで役立つ unzip コマンドの高度なオプションをいくつか探索してみましょう。
練習用の新しい ZIP ファイルの作成
高度なオプションを試すために、複数のファイルを含む新しい ZIP ファイルを作成しましょう。
## Create a new directory for our files
mkdir -p testdir/subdir
## Create some sample files in different locations
echo "This is a file in the main directory." > testdir/main.txt
echo "This is a file in the subdirectory." > testdir/subdir/sub.txt
## Compress the directory with all its contents
zip -r testarchive.zip testdir
## Remove the original directory to simulate receiving only the ZIP file
rm -rf testdir
これで、ディレクトリ構造とファイルを含む testarchive.zip という名前の ZIP ファイルができました。
詳細な出力で抽出する
抽出中により詳細な出力を得るには、-v(verbose)オプションを使用できます。
unzip -v testarchive.zip
これにより、アーカイブ内の各ファイルに関する詳細情報が表示されます。圧縮方法、圧縮後と解凍後のサイズなどが含まれます。
別のディレクトリに抽出する
デフォルトでは、unzip はファイルを現在のディレクトリに抽出します。別のディレクトリに抽出するには、-d オプションの後にターゲットディレクトリのパスを指定します。
## Create a directory to extract to
mkdir extraction_target
## Extract the ZIP file to the new directory
unzip testarchive.zip -d extraction_target
これで、testarchive.zip の内容が extraction_target ディレクトリに抽出されます。
特定のファイルを抽出する
ZIP アーカイブから特定のファイルのみを抽出したい場合は、アーカイブ名の後にファイル名を指定できます。
## First, let's list the contents to know what's available
unzip -l testarchive.zip
## Now, extract only the main.txt file
unzip testarchive.zip testdir/main.txt
既存のファイルを上書きせずに抽出する
抽出時に既存のファイルを上書きすることを心配する場合は、-n(never overwrite)オプションを使用できます。
unzip -n testarchive.zip
このオプションを使用すると、unzip は同じ名前の既存のファイルを上書きするファイルを抽出しません。
結果の確認
抽出した内容を確認しましょう。
## Check the extracted directory structure
ls -R testdir
## Check the extraction_target directory
ls -R extraction_target
これにより、先ほど作成したディレクトリ構造とファイルが表示されるはずです。
これらの高度なオプションを使用すると、ZIP アーカイブからファイルを抽出する方法をより細かく制御できます。これにより、unzip コマンドは Linux で圧縮ファイルを扱うための多目的なツールになります。