![](/img/trans.png)
[英]directories based on the filename and then move the associated files to the correct directories for random name
[英]Merge files to directories based on match of filename to directory name
我對腳本很陌生,所以請輕松。 我知道還有另一個論壇與此相關,但並未完全涵蓋我的問題。
我有一個包含文件的目錄和另一個包含我需要將每個文件移動到的相應文件夾的目錄。 每個文件對應於目標目錄,如:
DS-123.txt /DS-123_alotofstuffhere/
我想根據文件名的前 6 個字符與目錄的前 6 個字符的匹配來自動移動。
我有這個:
filesdir=$(ls ~/myfilesarehere/)
dir=$(ls ~/thedirectoriesareinthisfolder/)
for i in $filesdir; do
for j in $dir; do
if [[${i:6} == ${j:6}]]; then
cp $i $j
fi
done
done
但是當我運行腳本時,出現以下錯誤:
es: line 6: [[_DS-123_morefilenametext.fasta: command not found
我正在使用 Linux(不確定超級計算機上的版本,抱歉)。
最好使用數組和通配符來保存文件和目錄列表,而不是ls
。 通過該更改和對[[ ... ]]
部分的更正,您可以為我們編寫以下代碼:
files=(~/myfilesarehere/*)
dirs=(~/thedirectoriesareinthisfolder/*)
for i in "${files[@]}"; do
[[ -f "$i" ]] || continue # skip if not a regular file
for j in "${dirs[@]}"; do
[[ -d "$j" ]] || continue # skip if not a directory
ii="${i##*/}" # get the basename of file
jj="${j##*/}" # get the basename of dir
if [[ ${ii:0:6} == ${jj:0:6} ]]; then
cp "$i" "$j"
# need to break unless a file has more than one destination directory
fi
done
done
[[ -d "$j" ]]
檢查是必要的,因為您的dirs
數組也可能包含一些文件。 為了更安全,我還添加了一個檢查$i
是一個文件。
這是@triplee 建議的不使用數組的解決方案:
for i in ~/myfilesarehere/*; do
[[ -f "$i" ]] || continue # skip if not a regular file
for j in ~/thedirectoriesareinthisfolder/*; do
[[ -d "$j" ]] || continue # skip if not a directory
ii="${i##*/}" # get the basename of file
jj="${j##*/}" # get the basename of dir
if [[ ${ii:0:6} == ${jj:0:6} ]]; then
cp "$i" "$j"
# need to break unless a file has more than one destination directory
fi
done
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.