0

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
starball
  • 20,030
  • 7
  • 43
  • 238
M Suhayl
  • 27
  • 5
  • 1
    If the string is always the same format, you can [split it into an array](https://stackoverflow.com/q/10586153/12859753) and pull out the appropriate index. In this case, split on `-` and pull out the 4th piece. – Bill Jetzer Nov 10 '21 at 13:13
  • so the 4th - how would i do that? – M Suhayl Nov 10 '21 at 13:16

2 Answers2

3

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
Bill Jetzer
  • 1,105
  • 4
  • 6
0

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)

MrNonoss
  • 21
  • 7