Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading