使用shell脚本提取一个文件名,日期在UNIX [英] extract date from a file name in unix using shell scripting

查看:225
本文介绍了使用shell脚本提取一个文件名,日期在UNIX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的shell脚本。我想从一个文件名中提取日期。

该文件名为: abcd_2014-05-20.tar.gz

我想从中提取日期: 2014年5月20日


解决方案

 回声abcd_2014-05-20.tar.gz | grep的-eo[[:数字:]] {4 }  -  [[:数字:]] {2}  -  [[:数字:]] {2}

输出:

  2014年5月20日

的grep 得到输入作为回声标准输入,或者您也可以使用命令,如果你在一个文件中的这些字符串。

-E 国米preT图案作为扩展的正前pression。

-o 只显示匹配模式的匹配行的一部分。

[:数字:]]。它只会从输入取位

{N} 它会检查在给定的字符串位数N多,如: 4年2个月,天

更重要的是它将不使用任何分隔符,如_,并获取。这就是为什么它是最灵活的解决方案。

I am working on shell script. I want to extract date from a file name.

The file name is: abcd_2014-05-20.tar.gz

I want to extract date from it: 2014-05-20

解决方案

echo abcd_2014-05-20.tar.gz |grep -Eo '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}'      

Output:

2014-05-20

grep got input as echo stdin or you can also use cat command if you have these strings in a file.

-E Interpret PATTERN as an extended regular expression.

-o Show only the part of a matching line that matches PATTERN.

[[:digit:]] It will fetch digit only from input.

{N} It will check N number of digits in given string, i.e.: 4 for years 2 for months and days

Most importantly it will fetch without using any separators like "_" and "." and this is why It's most flexible solution.

这篇关于使用shell脚本提取一个文件名,日期在UNIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆