Nigu
Nigu

Reputation: 2135

How to use the pwd as a filename

I need to go through a whole set of subdirectories, and each time it finds a subdirectory named 0, it has to go inside it. Once there, I need to execute a tar command to compact some files.

I tried the following

find . -type d -name "0" -exec sh -c '(cd {} && tar -cvf filename.tar ../PARFILE RS* && cp filename.tar ~/home/directoryForTransfer/)' ';'

which seems to work. However, because this is done in many directories named 0, it will always overwrite the previous filename.tar one (and I lose the info about where it was created).

One way to solve this would be to use the $pwd as the filename (+.tar at the end).

I tried double ticks, backticks, etc, but I never manage to get the correct filename.

"$PWD"".tar", `$PWD.tar`, etc 

Any idea? Any other way is ok, as long as I can link the name of the file with the directory it was created.

I'd need this to transfer the directoryToTransfer easily from the cluster to my home computer.

Upvotes: 0

Views: 1595

Answers (2)

petersohn
petersohn

Reputation: 11730

You can try "${PWD//\//_}.tar". However you have to use bash -c instead of sh -c.

Edit:

So now your code should look like this:

find . -type d -name "0" -exec bash -c 'cd {} && tar -cvf filename.tar ../PARFILE RS* && cp filename.tar ~/home/directoryForTransfer/"${PWD//\//_}.tar"' ';'

I personally don't really like the using -exec flag for find as it makes the code less readable and also forks a new process for each file. I would do it like this, which should work unless a filename somewhere contains a newline (which is very unlikely).

while read dir; do
    cd {} && tar -cvf filename.tar ../PARFILE RS* && cp filename.tar ~/home/directoryForTransfer/"${PWD//\//_}.tar"
done < <(find . -type d -name "0")

But this is just my personal preference. The -exec variant should work too.

Upvotes: 1

anubhava
anubhava

Reputation: 785721

You can use -execdir option in find to descend in each found directory and then run the tar command to greatly simplify your tar command:

find . -type d -name "0" -execdir tar -cvf filename.tar RS* \;

If you want tar file to be created in ~/home/directoryForTransfer/ then use:

find . -type d -name "0" -execdir tar -cvf ~/home/directoryForTransfer/filename.tar RS* \;

Upvotes: 1

Related Questions