【问题标题】:Weird Issue Reading files with spaces (Shell script) [duplicate]奇怪的问题读取带有空格的文件(Shell 脚本)[重复]
【发布时间】:2019-04-27 09:50:13
【问题描述】:

这是我的代码:

#!/bin/bash

# https://askubuntu.com/a/343753
# http://wiki.bash-hackers.org/commands/builtin/read
# (use null character to separate a list of filenames)
# (sets IFS in the environment for just the read command)
log=./log.txt
OLDIFS=$IFS
find $1 -type f -name '*.MTS' -print0 |
while IFS= read -r -d '' input; do
    # set IFS to null string to preserve whitespace when $input is used
    IFS=''
    echo ""
    echo "input='${input}'"
    echo "`sha1sum "${input}"`"
    output="${input%.MTS}.mp4" # change extension to MTS
    ffmpeg -i "$input" -n -c:v copy -c:a aac -strict experimental -b:a 128k "$output" >> "$log" 2>&1
    if [ $? != 0 ]; then
        echo "FAILED: "$input" -> "$output""
    else
        touch -r "$input" "$output"  # copy original file's metadata
        echo "SUCCESS: "$input" -> "$output"" # indicate success
    fi

done
IFS=$OLFDIFS
echo "------"

请注意输出如何根据我是否注释掉 ffmpeg 行而发生变化:

我的问题是,为什么在使用 ffmpeg 命令时,读入的第二个文件名会变得混乱?

【问题讨论】:

标签: bash shell


【解决方案1】:

双引号不能引用双引号。像这样使用反斜杠:\"。例子:

echo "foo "bar     baz" bang"

输出,没有引号,没有空格:

foo bar baz bang

现在使用反斜杠:

echo "foo \"bar     baz\" bang"

输出,显示空格。

foo "bar     baz" bang

实际代码有这样两行:

echo "FAILED: "$input" -> "$output""

所以改成:

echo "FAILED: \"$input\" -> \"$output\""

【讨论】:

    【解决方案2】:

    Gordon 指出的答案是我必须放一个 /null

    在我的 ffmpeg 命令的最后,原因解释 here

    我确实遇到了一些双引号字符串的问题,但这不是这个问题的原因。谢谢大家!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-23
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 2016-01-10
      • 2011-03-11
      • 2016-06-04
      相关资源
      最近更新 更多