Issue
I have a folder called sync which includes files like :
vzdump-lxc-101-2018_06_07-02_23_11.tar
vzdump-lxc-101-2018_07_20-03_04_22.tar
vzdump-lxc-101-2018_08_17-03_34_11.tar
vzdump-lxc-101-2018_09_17-02_44_50.tar
vzdump-lxc-101-2019_01_19-00_16_02.tar
...
vzdump-lxc-104-2018_06_30-01_50_23.tar
vzdump-lxc-104-2018_07_20-03_18_56.tar
vzdump-lxc-104-2018_08_17-03_40_15.tar
vzdump-lxc-104-2018_10_19-01_52_00.tar
vzdump-lxc-104-2018_11_06-02_39_07.tar
vzdump-lxc-104-2019_01_19-00_24_14.tar
Ranging from vzdump-lxc-100 to vzdump-lxc-1xx etc..
I'm trying to loop over all files in a given directory and do a borg create (...) /path/to/repo::vzdump-lxc-$ID-$year_$month_$day "$f" but I'm not sure how to cut the name to just these three points
I tested it with the following : for f in vzdump-lxc*; do borg create (...) /path/to/repo::srv01_lxc_"$f" "$f";done
, but this gives me the full name which is too long including the leading vzdump-lxc, hour, minute, second and the extension maybe someone could lead me in the right direction.
I'm trying to achieve /path/to/repo::srv01_lxc_$id_$year_$month_$day
Cheers
Solution
You can split that name using '._-'
as the input field separator. Something like this:
IFS='-_.' read -ra path <<< vzdump-lxc-104-2019_01_19-00_24_14.tar
echo ${path[*]}
vzdump lxc 104 2019 01 19 00 24 14 tar
The code above creates an array path
with all the components split. After that, you can use any of them by referring its index:
echo ${path[3]}
2019
With that in mind, your code could something like this:
for f in vzdump-lxc*; do
IFS='-_.' read -ra p <<< $f
borg create (...) /path/to/repo::srv01_lxc_${p[2]}-${p[3]}-${p[4]}-${p[5]} "$f"
done
I hope that helps.
Answered By - accdias