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 ##
.
Example where I want to extract 20211021:
7_I-9112135749087-ZA_23-20211021-085359_2051521761_0000.zip
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 ##
.
Example where I want to extract 20211021:
7_I-9112135749087-ZA_23-20211021-085359_2051521761_0000.zip
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
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)