Reputation: 1810
I have some code that converts a date in a file name into a path.
#!/bin/bash
aFile="bla_2016-11-24_17-24.zip" # Many files, each with same format: "bla_{year}-{month}-{day}_{hour}-{minute}.zip"
aDate=${aFile#*_} # remove "bla_"
aDate=${aDate%.*} # remove ".zip"
aDate=${aDate//_/ } # replace "_" with " "
aDate=(${aDate//-/ }) # replace "-" with " " and make array
aPath="${aDate[0]}/${aDate[1]}/${aDate[2]}/${aDate[3]}/${aDate[4]}"
mkdir -p $aPath
I've seen both of these (1, 2), which suggest that nested parameter expansion expressions in bash scripting are not possible.
I was wondering if there might be a better way to implement my code above, more specifically reduce the length of the code. It's just five lines, so not a huge irritation if it's not possible, but it seems like I'm doing it in a dumb way.
Python solution:
aFile = "bla_2016-11-24_17-24.zip"
import re
aPath = "/".join(re.split("[_-]", aFile[4:-4])) # 2016/11/24/17/24
Upvotes: 0
Views: 90
Reputation: 6079
Here's a quicker Bash solution:
aFile="bla_2016-11-24_17-24.zip"
arr=($(echo ${aFile//[_-\.]/ }))
aPath=${arr[1]}/${arr[2]}/${arr[3]}/${arr[4]}/${arr[5]}
EDIT: This solution only works with recent versions of Bash such as the one shipped with Ubuntu 16.04 (4.3.46). It fails with 4.3.30 (shipped by Debian 8).
Upvotes: 1
Reputation: 88543
With bash:
aFile="bla_2016-11-24_17-24.zip"
[[ ${aFile//[_.-]//} =~ ^[^/]*/(.*)/[^/]*?$ ]] && echo "${BASH_REMATCH[1]}"
Output:
2016/11/24/17/24
Upvotes: 2
Reputation: 1810
Actually, I solved this. I tried a solution with sed then realised that's dumb; I could just use my Python solution. So for anyone wondering, here's mine:
aFile="bla_2016-11-24_17-24.zip"
aPath="$(python -c 'import sys, re; print "/".join(re.split("[_-]", sys.argv[1][4:-4]))' "$aFile")" # 2016/11/24/17/24
Upvotes: 0