0

I am struggeling a bit. As I write a ksh script I need to extract a Substring of a String where the number of occurances of the dilimiter is flexible.

This is, as my String holds the name of a file which might be compressed several times, therefore having more than 1 point (.). These points would be my delimiter, but as the supplier might include version numbers into the name of the file (e.g. software-v.3.2.4.tar.gz), I find no was to cut off the last suffix.

The progress is as follows:

Filename is saved in variable. File is decompressed first time. (taking the .gz suffix away of the file) Now I need to extract the .tar archive. But my command would still be holding the .gz suffix. Command would not work as the file has the suffix no more.

How do I get the suffix of my variable. I can not guarantee that the numbers of delimiters stay the same.

I tried several combinations of | rev | cur -d'.' | rev, but in this case I only get the suffix.

I aswell tried initialize the $fileName variable again with the actual name of the file, but therefore I would need to search the whole directory. I try to avoid that.

...

fileName="whole file name"
pathTo="path in which it should be moved after decompression"

if [ "$fileType" = "gz" ]; then

    gzip $pathTo$fileName -d $pathTo

    #Problem occurs right here

    tar xfv $pathTo$fileName -C $pathTo

else 
    echo "Unknown Filetype. Cannot decompress. Script stopped."
    exit

fi

...

I am thankful for any help. Greets

Yonkske

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
Yonkske
  • 13
  • 4

2 Answers2

0

Don't use | rev | cut -d'.' -f 1 | rev but use | rev | cut -d'.' -f 2- | rev

Walter A
  • 19,067
  • 2
  • 23
  • 43
0

Variable Substitution is the best choose here, as it is a shell built in it also the fastest.

filename='software-v.3.2.4.tar.gz'
echo ${filename##*.}

Output will be gz

This will not modify the value of the variable $filename.

if [[ "${filename##*.}" == "gz" ]]; then

How it work,

${var#pattern} - Use value of var after removing text that match pattern from the left

${var##pattern} - Same as above but remove the longest matching piece instead the shortest

${var%pattern} - Use value of var after removing text that match pattern from the right

${var%%pattern} - Same as above but remove the longest matching piece instead the shortest

There is more but this is the relevant ones here.

The Limitation of this they cannot be Nested.

lw0v0wl
  • 664
  • 4
  • 12