Search code examples
macosbashzipterminalarchive

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


Solution

  • 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