【问题标题】:while read with spaces in filenames读取文件名中的空格时
【发布时间】:2018-10-09 23:41:53
【问题描述】:

在这个.ogg 文件上

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

我尝试使用while 循环将它们转换为 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 时修复它

【问题讨论】:

    标签: bash while-loop ffmpeg


    【解决方案1】:

    使用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
    

    见:

    【讨论】:

    • 带有 shopt ... 的 for 循环效果很好;但是虽然没有奏效。 ffmpeg 挂在第一个文件的末尾:"""... 输出 #0,mp3,到 'mp3/./Disc 1 - 02 - À carreaux !.ogg.mp3':size= 378kB time=00:00 :24.16 bitrate= 128.2kbits/s speed=48.3x 输入命令:|all
    • @user3313834,将&lt;/dev/null 放在ffmpeg 行以阻止它使用标准输入。
    【解决方案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
    

    【讨论】:

    • 对于您的第一个答案,我猜\; 不见了
    • 第二次它起作用了,但我不明白最后的 _ {} 是什么
    • 当您运行sh -c '...' 时,下一个参数设置新shell 中$0 的值。你很少关心那个值是什么;我使用_ 作为虚拟值。 {}find 传递的当前文件,shell 以$1 访问该文件。
    猜你喜欢
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2011-03-09
    • 2013-05-25
    • 1970-01-01
    相关资源
    最近更新 更多