Performing grep operation in tar files without extracting

后端 未结 6 1379
梦谈多话
梦谈多话 2020-12-05 00:28

I have list of files which contain particular patterns, but those files have been tarred. Now I want to search for the pattern in the tar file, and to know which files conta

6条回答
  •  孤城傲影
    2020-12-05 01:02

    That's actually very easy with ugrep option -z:

    -z, --decompress
            Decompress files to search, when compressed.  Archives (.cpio,
            .pax, .tar, and .zip) and compressed archives (e.g. .taz, .tgz,
            .tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, and .txz) are searched and
            matching pathnames of files in archives are output in braces.  If
            -g, -O, -M, or -t is specified, searches files within archives
            whose name matches globs, matches file name extensions, matches
            file signature magic bytes, or matches file types, respectively.
            Supported compression formats: gzip (.gz), compress (.Z), zip,
            bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
            lzma and xz (requires suffix .lzma, .tlz, .xz, .txz).
    

    For example:

    ugrep -z PATTERN archive.tgz
    

    This greps each of the archived files to display PATTERN matches with the archived filenames. Archived filenames are shown in braces to distinguish them from ordinary filenames. Everything else is the same as grep (ugrep has the same options and produces the same output). For example:

    $ ugrep -z "Hello" archive.tgz
    {Hello.bat}:echo "Hello World!"
    Binary file archive.tgz{Hello.class} matches
    {Hello.java}:public class Hello // prints a Hello World! greeting
    {Hello.java}:  { System.out.println("Hello World!");
    {Hello.pdf}:(Hello)
    {Hello.sh}:echo "Hello World!"
    {Hello.txt}:Hello
    

    If you just want the file names, use option -l (--files-with-matches) and customize the filename output with option --format="%z%~" to get rid of the braces:

    $ ugrep -z Hello -l --format="%z%~" archive.tgz
    Hello.bat
    Hello.class
    Hello.java
    Hello.pdf
    Hello.sh
    Hello.txt
    

    Tarballs (.tar.gz/.tgz, .tar.bz2/.tbz, .tar.xz/.txz, .tar.lzma/.tlz) are searched as well as .zip archives.

提交回复
热议问题