Extract line from file in .tar.bz2 Archive

0

I'd like to use stdin/stdout on a single line to display the version from a file within a .tar.bz2 archive without affecting the existing archive or leaving any temporary files behind. The file only has one line containing version.

These commands work but they leave temporary files behind:

cp /storage/archive.tar.bz2 /tmp/
bunzip2 /tmp/archive.tar.bz2
tar -C /tmp -xvf /tmp/archive.tar dir1/dir2/file
cat /tmp/dir1/dir2/file | grep version

The version of busybox I am using has a restricted command set:

# bunzip2 --help
BusyBox v1.23.2 (2017-08-22 01:34:50 UTC) multi-call binary.

Usage: bunzip2 [-cf] [FILE]...

Decompress FILEs (or stdin)

        -c      Write to stdout
        -f      Force

# tar -h
BusyBox v1.23.2 (2017-08-22 01:34:50 UTC) multi-call binary.

Usage: tar -[cxtzhvO] [-X FILE] [-T FILE] [-f TARFILE] [-C DIR] [FILE]...

Create, extract, or list files from a tar file

Operation:
        c       Create
        x       Extract
        t       List
        f       Name of TARFILE ('-' for stdin/out)
        C       Change to DIR before operation
        v       Verbose
        z       (De)compress using gzip
        O       Extract to stdout
        h       Follow symlinks
        X       File with names to exclude
        T       File with names to include

flywire

Posted 2018-12-16T13:07:39.580

Reputation: 55

Answers

1

Use pipes – on nearly all recent operating systems, a pipe exists entirely in memory and does not require the full intermediate data to be stored.

Your version of tar does not have a -J option to call bzip2/bunzip2 (which would automatically use a pipe behind the scenes, just like -z does), but it does have -f - to read the archive from stdin. So you need to combine:

  1. Tell bunzip2 to write the output file to stdout: bunzip2 -c <file>
  2. Tell tar to read the archive from stdin: tar -x -f - ...
  3. Tell tar to write the extracted file to stdout: tar -O ...
  4. Tell grep to read the input from stdin.

The result is:

bunzip2 -c /storage/archive.tar.bz2 | tar -x -O -f - dir1/dir2/file | grep version

user1686

Posted 2018-12-16T13:07:39.580

Reputation: 283 655

Is it possible to put a character beside the - (stdin)? I'm getting en dash issues elsewhere. – flywire – 2018-12-16T21:05:05.860

You can pass -f- as a single arg, but uh, that's an odd mode of failure. – user1686 – 2018-12-16T23:05:52.783

Forum posting issue - not that odd for systems to reformat dash to en dash / em dash (eg word), anyway -xOf- fixed it for everyone – flywire – 2018-12-18T02:47:31.980