[英]How do I append parts of the directory names in a file's path to the file's name in bash or python?
最近,我使自己脫離了MacOS系統。 我最關心的是保留我在iPhoto中保存的十四年家庭圖像的價值。
我決定導出所有17000+張圖像,並將它們放入按年,月和日組織的文件夾樹中。 問題在於文件本身不包含有關何時拍攝圖像的信息。 標識何時拍攝圖像的唯一屬性是圖像所在的文件夾。
現在,我的“ Pictures”文件夾樹如下所示:
2004/
2005/
2006/
2007/
2008/
2009/
2010/
2011/
2012/
01_January/
02_February/
03_March/
04_April/
05_May/
06_June/
18June, 2012/
File - 001.jpg
File - 002.jpg
File - 003.jpg
etc...
24June, 2012/
File - 001.jpg
File - 002.jpg
File - 003.jpg
etc...
07_July/
08_August/
09_September/
10_October/
11_November/
12_December/
2013/
2014/
2015/
2016/
2017/
2018/
每年目錄包含十二個月的目錄。 僅當當天有圖像時,每個月目錄才包含日目錄。
我想要做的是附加所有圖像文件名,以便它們包括其上級目錄中的元素:
例:
./2012/06_June/18June, 2012/
File - 001.jpg -------> 2012-06-18_File - 001.jpg
File - 002.jpg -------> 2012-06-18_File - 002.jpg
File - 003.jpg -------> 2012-06-18_File - 003.jpg
etc...
有人可以幫我找到一種方法嗎? Python或Bash腳本,我可以用兩種方法學習如何做到這一點。 謝謝。
假設您位於“圖片”文件夾中,則可以嘗試以下代碼。 請首先檢查新名稱是否正確,然后取消注釋注釋行。
from glob import glob
import os
import re
for i in os.scandir(os.getcwd()):
if i.is_dir():
year = i.name
os.chdir(i.name)
for j in os.scandir(os.getcwd()):
if j.is_dir() and os.listdir(j.name):
month = re.compile(r'(\d+)').split(j.name)[-2]
os.chdir(j.name)
for k in os.scandir(os.getcwd()):
if k.is_dir():
day = re.compile(r'(\d+)').split(k.name)[-4]
os.chdir(k.name)
for l in glob('*.jpg'):
newName = year + '-' + month + '-' + day + '_' + l
print(l)
print(newName)
# os.rename(l, newName)
os.chdir('..')
os.chdir('..')
os.chdir('..')
這是一個( Shellcheck -clean)Bash解決方案:
#! /bin/bash
shopt -s nullglob # Globs that match nothing expand to nothing
for file_path in [12][0-9][0-9][0-9]/[01][0-9]_*/[0-3][0-9]*/*.jpg ; do
IFS=/ read -r year month_name day_month_year file_name <<<"$file_path"
month=${month_name%%[^0-9]*}
day=${day_month_year%%[^0-9]*}
day_month_year_path=${file_path%/*}
new_file_name=${year}-${month}-${day}_${file_name}
new_file_path=${day_month_year_path}/${new_file_name}
printf ' %s -------> %s\n' \
"$file_path" "$new_file_path" >&2
#UNCOMMENT mv -- "$file_path" "$new_file_path"
done
在包含Year目錄(2004,...)的目錄中運行它。
如果您滿意它會正確地重命名文件, #UNCOMMENT
從mv
行的開頭刪除#UNCOMMENT
並再次運行以實際重命名文件。
請參閱如何在Bash中的分隔符上拆分字符串? 有關IFS=/ read -r ... <<<"$file_path"
行的工作方式的詳細信息。
有關${var##pattern}
和${var%%pattern}
信息,請參閱刪除字符串的一部分(BashFAQ / 100(如何在bash中進行字符串處理?)) 。
有關模式的信息 ,請參閱glob-Greg的Wiki ,例如模式for
, */
和[^0-9]*
。
我擁有的解決方案是使用python,只需在PATH中查找所有文件,然后使用String的總和創建圖像名稱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.