Removing files extracted with tar
I untarred an archive today that didn’t have its files stored in a root directory, but instead heaved the 603 odd files and directories all over my Downloads folder. This often happens when unzipping as well, so I decided to string a few commands together to get rid of the “flotsam”.
The first step to get rid of the offenders is to get the names of all the files in the archive:
tar tf arch.tar.gz
The `t
` argument tells `tar
` to list the contents of the archive to standard output, including
./
Since we’re ultimately going to be sending files to `rm -rf
`, it would be disastrous to leave `./
` amongst the lines, since it will remove the contents of the entire directory. We’ll trim it (the first line of the output) from the list by specifying
tar tf arch.tar.gz | tail +2
`tail
` will ignore everything up until the n-th line when given `+n
`, so we effectively ignore the first line by using `+2
`. Now we can send each line to `rm -rf
` using
tar tf arch.tar.gz | tail +2 | xargs rm -rf
`xargs
` runs `rm -rf
` on each line that is piped to it, as if we specified each file manually. Once the files are removed we can `cd
` to a new directory and extract the files within it, leaving the containing directory clean and tidy.