4

I'm quite new to Bash so this might be something trivial, but I'm just not getting it. I'm trying to escape the spaces inside filenames. Have a look. Note that this is a 'working example' - I get that interleaving files with blank pages might be accomplished easier, but I'm here about the space.

#! /bin/sh

first=true
i=combined.pdf
o=combined2.pdf
for f in test/*.pdf
do
    if $first; then
        first=false
        ifile=\"$f\"
    else
        ifile=$i\ \"$f\"
    fi
    pdftk $ifile blank.pdf cat output $o
    t=$i
    i=$o
    o=$t
    break
done

Say I have a file called my file.pdf (with a space). I want the ifile variable to contain the string combined.pdf "my file.pdf", such that pdftk is able to use it as two file arguments - the first one being combined.pdf, and the second being my file.pdf.

I've tried various ways of escaping (with or without first escaping the quotes themselves, etc.), but it keeps splitting my and file.pdf when executing pdftk.

EDIT: To clarify: I'm trying to pass multiple file names (as multiple arguments) in one variable to the pdftk command. I would like it to recognise the difference between two file names, but not tear one file name apart at the spaces.

4

2 回答 2

7

将多个参数放入单个变量没有意义。相反,将它们放入一个数组中:

args=(combined.pdf "my file.pdf");

请注意,"my file.pdf"引用它是为了保留空格。

您可以像这样使用数组:

pdftk "${args[@]}" ...

这会将两个单独的参数传递给pdftk. 中的引号"${args[@]}"是必需的,因为它们告诉 shell 将每个数组元素视为一个单独的“单词”(即不要拆分数组元素,即使它们包含空格)。

作为旁注,如果您使用bash像数组这样的isms,请将您的shebang更改为

#!/bin/bash
于 2013-10-01T18:02:33.057 回答
0

尝试:

find test/*.pdf | xargs -I % pdftk % cat output all.pdf

正如我在对其他答案的评论中所说的那样,xargs这是最有效的方法。

编辑:我没有看到您需要空白页,但我想您可以将find上面的内容通过管道传递给某个命令以将空白页放在两者之间(类似于列表-> 字符串连接)。我更喜欢这种方式,因为它更像 FP。

于 2013-10-01T18:11:38.033 回答