在这里运行 Ubuntu Linux。
我有一个终端命令,可以查找 PWD 中的所有 mp3 文件,使用 mp3info 以分钟为单位获取它们各自的持续时间,对它们求和,并打印 pwd 中所有 mp3 的总持续时间。
for file in *.mp3; do
mp3info -p "%S\n" "$file"
done | paste -sd+ | sed 's+\(.*\)+(\1)/60+' | bc
输出示例:
$ for file in *.mp3; do
mp3info -p "%S\n" "$file"
done | paste -sd+ | sed 's+\(.*\)+(\1)/60+' | bc
47
所以,PWD 中有 47 分钟的 mp3。
我想将其制作成一个 bash 脚本,该脚本将递归到所有较低的目录,打印它们的名称,并列出每个文件夹中找到的所有 mp3 的总持续时间,例如:
foldernameA
45
foldernameB
89
foldernameC
17
ETC。
我尝试过的(“durations.sh”):
#!/bin/bash
find . -type d -execdir sh -c 'for file in *.mp3;
do
mp3info -p "%S\n" "$file";
done
| paste -sd+ | sed 's+\(.*\)+(\1)/60+' | bc
但这只是悲惨地失败了:
$ ./durations.sh
./durations.sh: line 6: syntax error near unexpected token `('
./durations.sh: line 6: `| paste -sd+ | sed 's+\(.*\)+(\1)/60+' | bc'
我显然不知道自己在做什么。
答案1
您可以直接使用 for 循环shopt -s globstar:
环球星
如果设置,文件名扩展上下文中使用的模式“**”将匹配所有文件以及零个或多个目录和子目录。如果模式后跟“/”,则仅目录和子目录匹配。
shopt -s globstar
d=0;
for file in **/*.mp3; do
d=$((d + $(mp3info -p "%S" "$file")))
done
mins=$(echo "$d / 60" | bc)
secs=$(echo "$d % 60" | bc)
echo "Total $mins minutes and $secs seconds"
答案2
如果你想列出单个文件夹的长度,你需要一个双循环。第一个循环列出目录,第二个循环列出每个目录中的文件:
#!/bin/bash
OIFS="$IFS"
IFS=$'\n'
function secondToTime () { #Convert second to Day, Hours, Minutes, Seconds
seconds=$1
min=0
hour=0
day=0
if((seconds>59));then
((sec=seconds%60))
((seconds=seconds/60))
if((seconds>59));then
((min=seconds%60))
((seconds=seconds/60))
if((seconds>23));then
((hour=seconds%24))
((day=seconds/24))
else
((hour=seconds))
fi
else
((min=seconds))
fi
else
((sec=seconds))
fi
echo "$day"d "$hour"h "$min"m "$sec"s
}
case $1 in #loop though the first argument
'-h'|'--help') # Display the help and exit
echo "Usage: $0 [PATH]"
echo "Display the total play time of each folder"
exit 0
;;
!'') # Will use the argument as target path
target=$1
;;
*) # If no argument is specify it will use the current path
target='.'
;;
esac
for folders in `find $1 -type d ` # Find all sub folders in the specifyed path
do
for folder in $folders # Loop though each folders
do
echo Folder $folder:
folderTime=0;
for file in `ls $folder/*.mp3 2> /dev/null` #loop though each files in each folders
do
fileTime=`mp3info -p "%S\n" "$file"` #get the time lenght of $file
isNumber=`echo $fileTime | grep -E '^\-?[0-9]+.?[0-9]*$'` #grep only numbers, if it's not a number isNumber will be empty
if [ "$isNumber" != '' ] # Check if $isNumber is NOT empty (which mean that it's a number)
then
let "folderTime=$fileTime+$folderTime" #Calculate Total duration in seconds
fi
done
secondToTime $folderTime # Convert seconds to days hours minutes seconds and print it out
done
done
IFS=$OIFS