我想从 Bash 中的这个字符串中提取日期并将其保存到变量中

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

我想从 Bash 中的这个字符串中提取日期并将其保存到一个变量中 但我面临的问题是有很多 - 我不能使用 ##

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

我要提取20211021请

谢谢

假设文件名始终采用相同的格式,您可以通过以下两种方式之一执行此操作。

仅使用字符串操作:

$ 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

使用数组:

$ 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

因为有一个可见的分隔符(-),我会简单地使用cut到select第四个范围:
$ var=$(echo "7_I-9112135749087-ZA_23-20211021-085359_2051521761_0000.zip" | cut -d "-" -f4)