[英]Move file to a directory with a given condition using Bash
首先,感谢您的帮助。 我在尝试将文件移动到目录时遇到问题。 我有下一个目录: Animals
Boat
Cars
我想移动以下文件Animals.txt
Boat.txt
和Car.txt
我想这样做,如果文件的名称与它移动到它的目录的名称匹配,而不是执行以下代码:
mv Animals.txt Animals
似乎您只需要一个简单的循环和一个参数扩展来从文件名派生目录名。
for txt in ./*.txt; do
dir=${txt%.*}
if [ -d "$dir" ]; then
echo mv "$txt" "$dir"
fi
done
如果 output 看起来不错,则丢弃echo
。
如果存在这样的目录,此脚本会将当前目录的所有*.txt
文件移动到相应的目录中。
for f in *.txt
do
# Avoid possible errors or unwanted commands in case there is no match for *.txt
if [ "$f" != '*.txt' ]
then
# strip trailing .txt
d="${f%.txt}"
# check if corresponding directory exists
if [ -d "$d" ]
then
mv "$f" "$d"
fi
fi
done
编辑:这个答案没有按预期工作,我错过了关于丢失目录的部分。 @oguz-ismail 给出的答案更好。
mkdir animals boat cars
touch animals.txt boat.txt cars.txt
for f in *.txt; do mv -v $f ${f/.txt}; done
renamed 'animals.txt' -> 'animals/animals.txt'
renamed 'boat.txt' -> 'boat/boat.txt'
renamed 'cars.txt' -> 'cars/cars.txt'
如果你安装mmv
,你可以在一行中没有循环(我假设目录已经存在):
mmv '*.txt' '#1'
我想将文件从目录中拉出(即与上述过程相反),您将执行以下操作:
mmv '*/*' '#2'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.