使用 shell 脚本从 unix 中的文件名中提取日期 [英] extract date from a file name in unix using shell scripting
问题描述
我正在编写 shell 脚本.我想从文件名中提取日期.
I am working on shell script. I want to extract date from a file name.
文件名为:abcd_2014-05-20.tar.gz
我想从中提取日期:2014-05-20
推荐答案
echo abcd_2014-05-20.tar.gz |grep -Eo '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}'
输出:
2014-05-20
grep
以 echo
标准输入的形式输入,或者如果文件中有这些字符串,您也可以使用 cat
命令.
grep
got input as echo
stdin or you can also use cat
command if you have these strings in a file.
-E
将 PATTERN 解释为扩展的正则表达式.
-E
Interpret PATTERN as an extended regular expression.
-o
仅显示匹配 PATTERN 的匹配行部分.
-o
Show only the part of a matching line that matches PATTERN.
[[:digit:]]
它只会从输入中获取数字.
[[:digit:]]
It will fetch digit only from input.
{N}
它将检查给定字符串中的 N 个数字,即: 4 表示年 2 表示月和日
{N}
It will check N number of digits in given string, i.e.: 4 for years 2 for months and days
最重要的是,它可以在不使用任何分隔符(如_"和.")的情况下进行获取.这就是为什么它是最灵活的解决方案.
这篇关于使用 shell 脚本从 unix 中的文件名中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!