0

I have lots of files that I want to archive/compress using 7zip utility. They all reside in the same folder. Each archive must have the same name as the file that is to be archived.

For example, if the files are 1.txt, 2.txt, 3.txt then the archives should be 1.7z, 2.7z and so on.

I have found some batch scripts, but I need a bash script.

I can list all the files using

for i in *.txt; do echo $i; done 

but cannot make it work with 7zip command, i.e. 7z a 'archive.7z' 'file.txt'

2 Answers 2

1
for i in *.txt; do 7z a "${i%%.*}.7z" "$i"; done 

This command seems to work. If your file name contains spaces, then try setting the delimiter to line-break. I achieved it by using this command IFS=$'\n'.

${i%%.*} this thing was used to remove the extension .txt in my case. If you want your archive to look like this .txt.7z then simply use $i.7z and it will work.

2
  • How can you extract the filename only from this so that the file destination can be defined as a different location? Commented Feb 1, 2024 at 21:29
  • 1
    Figured it out. for i in /path/to/input/files/*; do f=$(basename -- "$i"); 7z a "/path/to/outout/files/$f.7z" "$i"; done Commented Feb 1, 2024 at 21:49
1

pack multiple files in parallel:

ls *.txt | xargs -i -n 1 -P 12 7z a -mx=9 -sdel -stl -bso0 -bsp0 -y -- "{}.7z" "{}" 

where:

  • ls *.txt lists all txt files. one can also do cat my_filelist.lst
  • xargs -i -n 1 -P 12 - executes 7z with 12 parallel threads
  • -mx=9 - max compressing
  • -stl - assign file's date to 7z
  • -bso0 -bsp0 - suppress excessive 7z output to console. leaving errors.
  • -y - overwrite existing 7z archive if there is one
  • -sdel remove original file after successful compression
  • {} original filename
  • "{}.7z" - target archive name, could also be "/archive/{}.7z"

P.S. for big files might not really needed for 7z, as it compresses big files using several CPUs anyway.. but for many small files - efficient.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.