Using grep to search file exention

Discussion in 'General Computing' started by Kryyll, Mar 13, 2014.

  1. Kryyll

    Kryyll Active Member

    Dec 9, 2013
    Likes Received:
    I've been trying to write a bash script that searches for any compressed file(.tar, .tar.gz, .zip, etc) and them decompresses for you. However, I can't see to get grep to search for the file extensions. I've tried;
    grep *.tar /path/to/stuff
    but no luck. Any ideas?

  2. Snipert

    Snipert New Member

    Mar 13, 2014
    Likes Received:
    Best Answer
    grep is used to search plaintext files.
    .tar files are not compressed in plain text.

    Try typing-> cat foo.tar
    into a teminal. It'll spit out a bunch of binary info (which it should be)

    To grep a .tar file, try this:
    tar -tf foo.tar | grep searchphrase

    -t lists the content of the .tar file, -f specifies the tar file, | pipes the output (plaintext!) into grep, which then searches it.

    To search for all of them (.tar files) it sounds like you want to take each file, list its contents and grep the results. Sounds like a for loop.

    So I'd do -> for i in *.tar; do tar -tf $i | grep searchterm; done
    Kryyll likes this.
  3. MikeyD

    MikeyD Active Member

    Jul 23, 2013
    Likes Received:
    Snipert is right, a for loop will be the best way to iterate over them.

    Here is the beginning of a script that may help:
    list=`ls | egrep "*.t(gz|ar*)"`  # This will grab all .tar .tar.gz and .tgz files. Need to add an extra condition for .zip though.
    for LIST in $list; do
        printf "${LIST}\n" # this will iterate over all the files grepped by the previous command
    This obviously only prints out the name of each file. ls can be used if all the files you need are in a specific directory, otherwise you may want to consider using a find command (which has file type options that may be able to fulfill the same purpose, saving you from having to concoct a regular expression)

    In the for loop you'll probably want to use a case statement or if statements to denote the options to send to tar (.tgz and tar.gz files will need to -z option to uncompress versus the standard .tar) you can then un-tar each file individually within the loop.

Share This Page