IMTheNachoMan
IMTheNachoMan

Reputation: 5811

extract and delete files from one tar and add to another new one

I have a bzip2ed tar file and a text file with a list of files. I want to extract the files listed in the text file from the tar, add them to a new tar, and then delete them from the first tar.

For example, if I have a tar file like this:

$ tar -tvf test.tar.bz2
drwxrwxrwx nacho/nacho       0 2018-11-16 23:30 one/test/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/a
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/b
drwxrwxrwx nacho/nacho       0 2018-11-16 23:25 one/test/c/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/a
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/b
drwxrwxrwx nacho/nacho       0 2018-11-16 23:25 one/test/c/c/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/c/a
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/c/b
drwxrwxrwx nacho/nacho       0 2018-11-16 23:25 one/test/c/d/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/d/a
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/d/b
drwxrwxrwx nacho/nacho       0 2018-11-16 23:34 one/test/e/

And a text file with a list of files like this:

$ cat files_to_extract
one/test/b
one/test/e/
one/test/c/b
one/test/c/d/a

After it is done, this is what the original tar file should look like:

$ tar -tvf test.tar.bz2
drwxrwxrwx nacho/nacho       0 2018-11-16 23:30 one/test/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/a
drwxrwxrwx nacho/nacho       0 2018-11-16 23:25 one/test/c/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/a
drwxrwxrwx nacho/nacho       0 2018-11-16 23:25 one/test/c/c/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/c/a
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/c/b
drwxrwxrwx nacho/nacho       0 2018-11-16 23:25 one/test/c/d/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/d/b

And what the new tar file should look like.

$ tar -tvf new.tar.bz2
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/b
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/b
drwxrwxrwx nacho/nacho       0 2018-11-16 23:34 one/test/e/
-rw-rw-rw- nacho/nacho       0 2018-11-16 23:25 one/test/c/d/a

Note, the order of the files is irrelevant.

Upvotes: 1

Views: 284

Answers (1)

Here's how I did it:

Extract files from "files_to_extract" to stdout and pipe to another tar:

tar -xOjf test.tar.bz2 -T files_to_extract | tar -cjf new.tar.bz2 -T -

Unzip, delete from tar and bzip it again:

bunzip2 test.tar.bz2
tar -f test.tar --delete $(cat files_to_extract)
bzip2 test.tar

Uncommon options documentation:

Upvotes: 1

Related Questions