Year Month day from file name in shell script

awkscriptingshell-scripting

I hava file names like below

adn_DF9D_20140515_0001.log
adn_DF9D_20140515_0002.log
adn_DF9D_20140515_0003.log
adn_DF9D_20140515_0004.log
adn_DF9D_20140515_0005.log
adn_DF9D_20140515_0006.log
adn_DF9D_20140515_0007.log

i want get the year, Month, day from file name and create directories

Ex: [[ ! -d "$BASE_DIR/$year/$month/$day" ]] && mkdir -p "$BASE_DIR/$year/$month/$day";

How to achieve this and share the ideas/ script appreciate to you

Best Answer

If the file name is always like in your example you can use something like:

for x in *.log; do year=${x:9:4}; month=${x:13:2}; day=${x:15:2}; [[ ! -d "$year/$month/$day" ]] && mkdir -p "$year/$month/$day"; done

This substring extraction is available in bash, not sure about other shells.

Related Topic