用文件名中的空格读取

时间:2018-04-29 20:29:45

标签: bash while-loop ffmpeg

在此.ogg个文件

$ tree
.
├── Disc 1 - 01 - Procrastination.ogg
├── Disc 1 - 02 - À carreaux !.ogg
├── Disc 1 - 03 - Météo marine.ogg
└── mp3

我尝试使用while循环将ffmpeg转换为mp3,保留文件名中的空格::

$ ls *.ogg | while read line; do ffmpeg -i "$line" mp3/"$line".mp3 ; done

但是我收到了这个错误::

$ ls *.ogg | while read line; do ffmpeg -i "$line" mp3/"$line".mp3 ; done
...
Parse error, at least 3 arguments were expected, only 0 given
in string ' 1 - 02 - À carreaux !.ogg' ...
...

此报告bash ffmpeg find and spaces in filenames即使看起来相似也是一个更复杂的脚本而且没有答案。

ffmpeg not working with filenames that have whitespace仅在输出为http:// URL

时修复此问题

2 个答案:

答案 0 :(得分:6)

使用find -print0获取NUL分隔的文件列表,而不是解析ls输出,这绝不是一个好主意:

#!/bin/bash

while read -d '' -r file; do
  ffmpeg -i "$file" mp3/"$file".mp3 </dev/null
done < <(find . -type f -name '*.ogg' -print0)

您也可以使用简单的glob来执行此操作:

shopt -s nullglob # make glob expand to nothing in case there are no matching files
for file in *.ogg; do
  ffmpeg -i "$file" mp3/"$file".mp3
done

请参阅:

答案 1 :(得分:2)

你不需要在这里循环;让find为你执行命令。

find . -type f -name '*.ogg' -exec ffmpeg -i {} mp3/{}.mp3 \;

或者,如果您想从结果中删除.ogg扩展名:

find . -type f -name '*.ogg' -exec sh -c 'ffmpeg -i "$1" mp3/"${1%.ogg}.mp3"' _ {} \;

相反,您可以完全跳过find

shopt -s extglob
for f in **/*.ogg; do
  [[ -f $f ]] || continue
  ffmpeg -i  "$f" mp3/"${f%.ogg}.mp3"
done