![](/img/trans.png)
[英]How can I make shell script to recursively scan a directory and add certain files based on their name patterns to Git?
[英]How can I make a bash script where I can move certain files to certain folders which are named based on a string in the files?
這是我用來將帶有字符串“john”的文件(124334_john_rtx.mp4、3464r64_john_gty.mp4 等)移動到某個文件夾的腳本
find /home/peter/Videos -maxdepth 1 -type f -iname '*john' -print0 | \
xargs -0 --no-run-if-empty echo mv --target-directory=/home/peter/Videos/john/
由於我在文件中有大量具有各種名稱的視頻,因此我想制作一個 bash 腳本,該腳本將帶有下划線之間的字符串的視頻移動到基於下划線之間的字符串命名的文件夾中。 因此,例如,如果文件名為 4345655_ben_rts.mp4,腳本將識別下划線之間的字符串“ben”,創建一個名為下划線之間的字符串的文件夾,在本例中為“ben”,並將文件移動到該文件夾。 任何意見是極大的贊賞 !
這個 bash 循環應該可以滿足您的需要:
find dir -maxdepth 1 -type f -iname '*mp4' -print0 | while IFS= read -r -d '' file
do
if [[ $file =~ _([^_]+)_ ]]; then
TARGET_DIR="/PARENTPATH/${BASH_REMATCH[1]}"
mkdir -p "$TARGET_DIR"
mv "$file" "$TARGET_DIR"
fi
done
如果找到目錄令牌,它只會移動文件。
我使用_([^_]+)_
來確保目錄名中沒有_
,但是如果文件名中有兩個以上的_
,則您沒有指定所需的內容。 如果foo_bar_baz_buz.mp4
用於 go 到目錄bar_baz
中, _(.+)_
將起作用。
這個對另一個問題的回答解釋了這個find | while
find | while
邏輯: https://stackoverflow.com/a/64826172/3216427 。
編輯:根據評論中的問題,我添加了mkdir -p
來創建目標目錄。 -p
表示遞歸創建路徑中不存在的任何部分,如果完整目錄已經存在,則不會出錯。
我的做法:
cd /home/peter/Videos # Change directory to your start directory
for name in $(ls *.mp4 | cut -d'_' -f2 | sort -u) # loops on a list of names after the first underscore
do
mkdir -p /home/peter/Videos/${name} # create the target directory if it doesn't exist
mv *_${name}_*.mp4 /home/peter/Videos/${name} # Moving the files
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.