user302581
user302581

Reputation: 43

How to archive files under certain dir that are not text files in Mac OS?

Hey, guys, I used zip command, but I only want to archive all the files except *.txt. For example, if two dirs file1, file2; both of them have some *.txt files. I want archive only the non-text ones from file1 and file2.

tl;dr: How to tell linux to give me all the files that don't match *.txt

Upvotes: 1

Views: 209

Answers (3)

bobbogo
bobbogo

Reputation: 15483

$ zip -r zipfile -x'*.txt' folder1 folder2 ...

Upvotes: 4

SiegeX
SiegeX

Reputation: 140367

Simple, use bash's Extended Glob option like so:

#!/bin/bash

shopt -s extglob

zip -some -options !(*.txt)

Edit

This isn't as good as the -x builtin option to zip but my solution is generic across any command that may not have this nice feature.

Upvotes: 0

sidyll
sidyll

Reputation: 59287

Move to you desired directory and run:

ls | grep -P '\.(?!txt$)' | zip -@ zipname

This will create a zipname.zip file containing everything but .txt files. In short, what it does is:

  1. List all files in the directory, one per line (this can be achieved by using the -1 option, however it is not needed here as it's the default when output is not the terminal, it is a pipe in this case).
  2. Extract from that all lines that do not end in .txt. Note it's grep using a Perl regular expression (option -P) so the negative lookahead can be used.
  3. Zip the list from stdin (-@) into zipname file.

Update

The first method I posted fails with files with two ., like I described in the comments. For some reason though, I forgot about the -v option for grep which prints only what doesn't match the regex. Plus, go ahead and include a case insensitive option.

ls | grep -vi '\.txt$' | zip -@ zipname

Upvotes: 0

Related Questions