Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash parse filename

Is there any way in bash to parse this filename :

$file = dos1-20120514104538.csv.3310686

into variables like $date = 2012-05-14 10:45:38 and $id = 3310686 ?

Thank you

like image 419
pufos Avatar asked May 16 '12 11:05

pufos


1 Answers

All of this can be done with Parameter Expansion. Please read about it in the bash manpage.

$ file='dos1-20120514104538.csv.3310686'
$ date="${file#*-}" # Use Parameter Expansion to strip off the part before '-'
$ date="${date%%.*}" # Use PE again to strip after the first '.'
$ id="${file##*.}" # Use PE to get the id as the part after the last '.'
$ echo "$date"
20120514104538
$ echo "$id"
3310686

Combine PEs to put date back together in a new format. You could also parse the date with GNU date, but that would still require rearranging the date so it can be parsed. In its current format, this is how I would approach it:

$ date="${date:0:4}-${date:4:2}-${date:6:2} ${date:8:2}:${date:10:2}:${date:12:2}"
$ echo "$date"
2012-05-14 10:45:38
like image 185
kojiro Avatar answered Sep 20 '22 20:09

kojiro