0

I have a directory with scsv files like this:

file1.scsv
file1_key.scsv
file1_flag.scsv
file1_typelist.scsv
files2.scsv
filass3.scsv
file4.scsv
file4_key.scsv
file4_flag.scsv
file5.scsv

i.e. you have file1, files2, filass3, etc. as prefixes. the prefix length varies quite alot, so i can't rely on that. the suffixes _key, _flag and _typelist are always the same and wont change.

and i would like to zip them like this:

file1.zip 
     #contains 
     file1.scsv
     file1_key.scsv
     file1_flag.scsv
     file1_typelist.scsv
files2.zip 
     #contains 
     files2.scsv
filass3.zip 
     #contains 
     filass3.scsv
file4.zip 
     #contains 
     file4.scsv
     file4_key.scsv
     file4_flag.scsv
file5.zip 
     #contains 
     file5.scsv

I'm quite new to bash/linux, so I tried following How to zip files with same name but different extension? as an example, but this assumes the files have precisely the same name before the extension.

0

1 Answer 1

1

I’m assuming that

files2.zip 
     #contains 
     files2.scsv
filass3.zip 
     #contains 
     filass3.scsv

is acceptable; otherwise you’d have to clarify the file name transformation rules.

for file in *.scsv; do
  if [[ ! "$file" =~ _ ]]; then
    base="${file%.scsv}"
    zip -9 "${base}.zip" "${file}" "${base}_*.scsv"
  fi
done

will look at each file with a .scsv extension, and if its name doesn’t contain “_”, create a ZIP file named after it (with .zip instead of .scsv), containing the file and any other files with the same prefix following by an underscore.

There’s a small trick here: I’m relying on zip’s wildcard handling instead of the shell’s, to avoid dealing with issues when there is no other file to add. zip will warn about this but won’t abort.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .