【问题标题】:How to assign file names with spaces to vectors?如何将带空格的文件名分配给向量?
【发布时间】:2013-08-07 08:37:45
【问题描述】:

我是 R 用户,并且正在尝试将 for 循环与在 bash (FFmpeg) 中运行的程序一起使用。创建一个向量然后在 for 循环中使用该向量对我来说似乎很自然。例如,这就是我在 R 中要做的:

f <- c("File name that is identifier 01.avi", "File name that is identifier 02.avi", "File name that is identifier 03.avi")

for i in 1:length(f) {for loop}

如何在 bash 中为向量分配名称?

这是我尝试并遇到以下问题的方法:

f=["File name that is identifier 01.avi" "File name that is identifier 02.avi" "File name that is identifier 03.avi"]
bash: File name that is identifier 02.avi: command not found

Bash 似乎将我的文件名识别为命令并在这种情况下运行它们

let f=["File name that is identifier 01.avi" "File name that is identifier 02.avi" "File name that is identifier 03.avi"]
bash: let: f=[File name that is identifier 01.avi: syntax error: operand expected (error token is "[File name that is identifier 01.avi")

我显然做错了什么。

如果我只对一个文件执行此操作,它会起作用。有无括号:

f=["File name that is identifier 01.avi"]
# echo $f
[File name that is identifier 01.avi]

【问题讨论】:

    标签: bash vector filenames assign


    【解决方案1】:

    bash 中,您可以通过以下方式拥有一个数组

    f=("File name that is identifier 01.avi" "File name that is identifier 02.avi" "File name that is identifier 03.avi")
    

    ${f[0]}${f[1]}{f[2]} 会返回文件名。

    为了遍历数组,你可以说:

    for ((i = 0; i < ${#f[@]}; i++))
    do
        echo "${f[$i]}"
    done
    

    会返回:

    File name that is identifier 01.avi
    File name that is identifier 02.avi
    File name that is identifier 03.avi
    

    或者,您也可以循环说:

    for i in "${f[@]}"; do echo "$i"; done
    

    【讨论】:

    • 我知道我不应该感谢 cmets,但您的回答非常有帮助。谢谢你,并继续在 SO =)
    【解决方案2】:

    唯一真正明智的方法是使用位置参数调用 bash 脚本(我不知道如何从 R 调用程序,所以这是伪代码):

    exec(["bash", "-c", "echo one: $1, two: $2", "--", "eins", "zwei")
    

    这里,-- 标志着 bash 选项的结束,并使所有后续参数(在本例中为 einszwei)为脚本本身的位置参数。

    在脚本中嵌入单词有一种简单、便携且安全的方法:将单个单词的所有关键(或简单地说,所有)字符转义为 \,并用空格分隔单词:

    system("myfunction my\ first\ arg\$\%\" my\ second\ arg\&\/\%")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 2022-01-06
      • 2015-04-27
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      相关资源
      最近更新 更多