bash7zipextglob

How to 7zip each file individually without the file extension included in the archive name?


I am trying to organize a large group of files for use with another program that can run them archived but only if they are named for example "My Document.7z" and not "My Document.txt.7z". The best solution I could come up with as linux doesn't have a variable for just grabbing the file name without the extension (%%~ni in Batch) was to just use regex to delete the last 4 characters (".txt" in this example) of the file name and then assign that variable to the title of the archive name creation command. I'm aware that this breaks files that have 2 and 4 letter extensions like .sh and .jpeg but I've been stumped for so long I'm honestly beyond caring at this point.

The code I've come up with so far is roughly:

#!/bin/bash
shopt -s extglob
for f in *.* ; do
f$ !(*.sh)
 g=$($f-4) #placeholder code for delete last 4 characters of filename syntax
 7z a $g.7z $f -sdel
done
read -p "pause"
exit
  1. Enable Bash script
  2. Enable extglob expressions (!)
  3. Grab any file in the current directory that has a "." in the name between groups of letters (any file with an extension, should avoid any folders)
  4. Further refines the variable "f" to not include .sh files (otherwise this script would be compressed and deleted)
  5. Placeholder code for regex to remove the last 4 characters of the variable "f" and assign it to the variable "g".
  6. Code for 7zip to create a .7z archive named 4 characters shorter than "f" and containing a file named whatever "f" was and then delete the original file.
  7. Finishes that part of the loop.
  8. Pausing the code to view errors or whatever before closing.
  9. closes the script.

Solution

  • Try:

    #!/bin/bash
    for f in *.* ; do
      if [[ $f == *.sh ]] || ! [[ -f $f ]]; then
        continue
      fi
      g=${f%.*}
      7z a "$g.7z" "$f" -sdel
    done
    read -p "pause"
    exit
    

    Notes: