4

I have a directory of compressed directories, like this:

MainDirectory/FolderA.tar.gz
MainDirectory/FolderB.tar.gz

Within each directory, some of the files have the same name. Ex.

MainDirectory/FolderA.tar.gz/file1.fasta
MainDirectory/FolderA.tar.gz/file2.fasta
MainDirectory/FolderB.tar.gz/file1.fasta
MainDirectory/FolderB.tar.gz/file1.fasta

I need to decompress each directory, rename each file with the name of the directory, and then recompress the individual files. My desired output is:

MainDirectory/FolderA_file1.fasta.bz2
MainDirectory/FolderA_file2.fasta.bz2
MainDirectory/FolderB_file1.fasta.bz2
MainDirectory/FolderB_file1.fasta.bz2

I came up with this code, but it renames the files to have a literal $f in:

cd MainDirectory/
for f in *.tar.gz
    do
    tar -xvzf $f --transform 's,^,${f},' 
    pbzip2 *.fastq 
    done

Output:

MainDirectory/'${f}file1.fastq.bz2'
MainDirectory/'${f}file2.fastq.bz2'

Please may you help me convert the command so it prepends the files with the actual folder name instead? Thank you.

2

With the GNU implementation of tar (your --transform is also a GNU extension anyway), you could do:

cd MainDirectory &&
  for f in *.tar.gz; do
    PREFIX=${f%.tar.gz} tar -xvvzf "$f" --to-command='
      pbzip2 > "${PREFIX}_$TAR_FILENAME.bz2"'
  done
0
2

Doing the extraction and recompression in two steps:

cd MainDirectory && for f in *.tar.gz; do
  tar --transform="s,^,${f%.tar.gz}_," --show-transformed-names -xvzf "$f"
done && pbzip2 *.fasta

Option --show-transformed-names and -v are only used to display the transformed filenames.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.