简体   繁体   中英

How to create zip archive with files with only .txt extension in Linux using terminal

I have directory "Documents" with these files:

file1.txt.

file2.txt

index.html

index.php

script.pl

I want to create zip archive named files.zip with only .txt extension files using terminal. How can I do these?

At the basic level, if you are in the same directory that your files are in, you can do :

zip files.zip *txt

And if you want to zip the files with .txt extention, by giving the absolute path, if they are in Documents directory, which will create files.zip in the current directory you are in:

zip files.zip /the/path/to/Documents/*txt

If you also want this zipped file to be in Documents folder, you should specify it as:

zip /the/path/to/Documents/files.zip /the/path/to/Documents/*txt

An add-on to the existing answer, if you are adding to an existing zip archive, be careful if you have identically named entries in the zip archive & the inpath . From man zip :

Command format. The basic command format is

 zip options archive inpath inpath ...

where archive is a new or existing zip archive and inpath is a directory or file path optionally including wildcards. When given the name of an existing zip archive, zip will replace iden‐ tically named entries in the zip archive (matching the relative names as stored in the archive) or add entries for new names. For example, if foo.zip exists and contains foo/file1 and foo/file2, and the directory foo contains the files foo/file1 and foo/file3, then:

 zip -r foo.zip foo

or more concisely

 zip -r foo foo

will replace foo/file1 in foo.zip and add foo/file3 to foo.zip. After this, foo.zip contains foo/file1, foo/file2, and foo/file3, with foo/file2 unchanged from before.

So if before the zip command is executed foo.zip has:

 foo/file1 foo/file2

and directory foo has:

 file1 file3

then foo.zip will have:

 foo/file1 foo/file2 foo/file3

where foo/file1 is replaced and foo/file3 is new.

Give a try to:

zip only-txt.zip `find . -name "*.txt"`

This will create a zip file named only-txt.zip including all the *.txt files located within the directory you run the command, notice that this will search for *.txt files recursively in all subfolders of the dir

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM