Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract date from a file name in unix using shell scripting

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

like image 666
priyanka Avatar asked Nov 12 '14 07:11

priyanka


1 Answers

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.

like image 69
Skynet Avatar answered Nov 07 '22 15:11

Skynet