I need to extract dates (year,month,day) and times (hour,minutes) from a text file and use them later as variables. Not a homework, just trying to do something useful for my work. I am new to Linux.

INPUT: The text file contains list of files named like:


Desired output is:

2010 02 03 12 10

I'd like to put them separately into few variables: year, month, day, hour, minutes. Should I use grep? Or sed? Or awk? Did a lot of reading, but feel stressed by amount of possibilities. Is it possible to write expression like "4 numbers after the string S3G_MX_1_EFR____ is "year"? I don't need complete code, just need a bit of advice what options/commands to use or where to start.


With GNU grep and bash:

timestamp=$( echo "$filename" | grep -oP '(?<=\D)\d{8}T\d{4}' )


year=${timestamp:0:4};    echo $year      # => 2010
month=${timestamp:4:2};   echo $month     # => 02
day=${timestamp:6:2};     echo $day       # => 03
hour=${timestamp:9:2};    echo $hour      # => 12
minute=${timestamp:11:2}; echo $minute    # => 10

Actually, plain bash will do (need version 4+)

if [[ $filename =~ $regex ]]; then
    echo "$year $month $day $hour $minute"
2010 02 03 12 10
  • Thank you! I loved the plain bash solution. Worked perfectly. But I had a problem with adding 3 extra columns for /other numbers (end date and time). like this: {regex='_([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})_([0-9]{8})T([0-9]{2})([0-9]{2})'} The file name is S3G_MX_1_EFR____20100203T121015_20100203T1315 - am I doing smth wrong? I also added {endate=${BASH_REMATCH[6]} hh=${BASH_REMATCH[7]} mm=${BASH_REMATCH[8]}} Actually I need only the second time(dont need enddate, but dont get any output of script as soon as I add this.
    – I V
    Oct 15 '19 at 8:37
  • There are 6 digits after the "T" Oct 15 '19 at 9:45
  • Thank you! My mistake.
    – I V
    Oct 15 '19 at 10:47

How about you do a replacement like

sed -E 's/.*S3G_MX_1_EFR____(....)(..)(..)T(..)(..).*/export year=\1 month=\2 day=\3 hour=\4 minute=\5/'

Those patterns like (....) (extended regular expression syntax) match the four digits after the pattern and can be used in the replacement as \1 and following. So the result for your example will be

export year=2010 month=02 day=03 hour=12 minute=10

This lines can be executed, e.g.

$(echo S3G_MX_1_EFR____20100203T121015_othernumbers.zip | sed -E 's/.*S3G_MX_1_EFR____(....)(..)(..)T(..)(..).*/export year=\1 month=\2 day=\3 hour=\4 minute=\5/')
  • Thanks for your help!
    – I V
    Oct 15 '19 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.