Home > database >  I want to Extract the date from this string in Bash and save it to a variable
I want to Extract the date from this string in Bash and save it to a variable

Time:11-11

I want to Extract the date from this string in Bash and save it to a variable but the problem im facing is there are many - and I cant use ##

7_I-9112135749087-ZA_23-20211021-085359_2051521761_0000.zip

I want to extract 20211021 Please

Thanks

CodePudding user response:

Assuming the filenames are always in the same format, you can do this in one of two ways.

Using just string manipulation:

$ file="7_I-9112135749087-ZA_23-20211021-085359_2051521761_0000.zip";

$ file=${file%-*};  # remove last dash through end of string
$ file=${file##*-}; # remove everything up to last remaining dash

$ echo "$file";
20211021

Using an array:

$ file="7_I-9112135749087-ZA_23-20211021-085359_2051521761_0000.zip";
$ IFS="-" read -ra parts <<< "$file";  # split into 0-based array using "-" as delimiter
$ echo ${parts[3]}; # 4th index
20211021

CodePudding user response:

Since there is a visible separator (-), I would simply use cut to select the fourth range:
$ var=$(echo "7_I-9112135749087-ZA_23-20211021-085359_2051521761_0000.zip" | cut -d "-" -f4)

  • Related