首页 > 解决方案 > 从shell中的文件名中提取时间戳部分

问题描述

我有一个像SID_Statistics_20191127.xlsx这样的文件名。我只需要从 shell 中的文件中提取时间部分。时间部分可能会改变,但格式保持不变

标签: shellunix

解决方案


请您尝试以下操作。

for file in *.xlsx; do val="${file##*_}";echo "${val%.*}"; done

或非单线形式的解决方案是:

for file in *.xlsx
do
  val="${file##*_}"
  echo "${val%.*}"
done

以上将遍历所有.xslx文件并打印时间戳。请参阅https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html链接,了解有关@user1934428 评论的参数扩展的更多详细信息。

说明:为上述代码添加详细级别的说明:

for file in *.xlsx          ##Starting for loop which will traverse through all xlxs format files.
do
  val="${file##*_}"         ##Creating a variable val whose value will be 20191127.xlsx, what it does is, it substitutes everything till _ last occurrence with NULL.
  echo "${val%.*}"          ##Doing substitution from DOT to till end of variable val value with NULL and printing which will print timestamp as per OP need.
done                        ##Closing this specific program for loop here.

推荐阅读