camdixon
camdixon

Reputation: 882

How to unpack .tgz file using Ruby

What I need is to untar / unzip random file names ending with .tgz

When I use irb (interpreted ruby via command line) this command works

`tar xzf *.tgz`

as long as I am in the appropriate directory

However, this doesn't work inside the ruby script. I change directory by using

puts Dir.pwd
Dir.chdir("unprocessed/") do
   puts Dir.pwd
end
`tar xzf *.tgz`

This puts me in the subdirectory unprocessed, and then I try to run the tar command above. It however gives me this error, but the same exact thing works in irb.

tar (child): *.tgz: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now

What I need is to untar / unzip random file names ending with .tgz Then I'm going to read what is inside of those.

EDIT ---- With the help of the accepted answer, I ended up using

Dir.chdir("unprocessed/") do
    puts Dir.pwd
    `tar xzf #{Dir.pwd}/*.tgz`
end

Upvotes: 1

Views: 969

Answers (1)

bjhaid
bjhaid

Reputation: 9762

The backticks evokes a new shell that knows nothing about Dir.pwd so what you want is something like this:

Dir.chdir("unprocessed/") do
   `tar xzf #{Dir.pwd}*.tgz`
end

or

Dir.chdir("unprocessed/")
`tar xzf #{Dir.pwd}*.tgz`

Upvotes: 2

Related Questions