0

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
dǝɥɔS ʇoıןןƎ
  • 1,674
  • 5
  • 19
  • 42
  • With GNU sed: `echo "bla_2016-11-24_17-24.zip" | sed -E 's/^[^_]+_(.*)\.zip$/\1/;s|[_-]|/|g'` Output: `2016/11/24/17/24` or with awk: `echo "bla_2016-11-24_17-24.zip" | awk -F '[_.-]' '{OFS="/"; print $2,$3,$4,$5,$6}'` – Cyrus May 07 '17 at 19:21
  • Nice solutions, I like them – dǝɥɔS ʇoıןןƎ May 07 '17 at 20:42

3 Answers3

2

With bash:

aFile="bla_2016-11-24_17-24.zip"
[[ ${aFile//[_.-]//} =~ ^[^/]*/(.*)/[^/]*?$ ]] && echo "${BASH_REMATCH[1]}"

Output:

2016/11/24/17/24
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

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).

Ricardo Branco
  • 5,740
  • 1
  • 21
  • 31
  • The problem is with the version of Bash. With version 4.1.5 (from the Docker image of Debian 6) it fails. My version is 4.3.46 (from Ubuntu 16.04). I fear we must debug our bashisms on older versions... :( Which version is yours? – Ricardo Branco May 09 '17 at 17:45
  • I was thinking the same. On MacOS though so my version was `3.2.57` or something similar. I updated, now I have `4.4.12`. I guess the latest version is too high? :o – dǝɥɔS ʇoıןןƎ May 09 '17 at 17:58
  • I think it's better than having that old version. Ubuntu 17.04 uses 4.4.5 and the upcoming Debian 9 4.4.11. – Ricardo Branco May 09 '17 at 18:03
0

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
dǝɥɔS ʇoıןןƎ
  • 1,674
  • 5
  • 19
  • 42