如何在没有组合爆炸的情况下进行多个大括号扩展?

Ber*_*ard 5 command-line bash brace-expansion

我经常在命令行上使用大括号扩展,因为它很方便。

例子

{foo,bar}
Run Code Online (Sandbox Code Playgroud)

扩展为:

foo bar
Run Code Online (Sandbox Code Playgroud)

多大括号扩展也扩展,例如:

{foo,bar}Q{foo,bar}
Run Code Online (Sandbox Code Playgroud)

将扩展为:

fooQfoo fooQbar barQfoo barQbar
Run Code Online (Sandbox Code Playgroud)

这是预期的行为,其中大括号扩展按顺序使用。

我的问题

现在,我希望任何大括号扩展(或其他简短的命令行技巧)的输出为:

fooQfoo barQbar
Run Code Online (Sandbox Code Playgroud)

注意:我正在使用 bash 3.2

Izk*_*ata 6

我同意 slm;我从来没有见过只用大括号扩展来做到这一点的方法。

但是,使用问题中的示例,我认为获得所需输出的最简单方法是使用循环,而不是大括号扩展和额外的后处理:

$ echo $(for X in foo bar;do echo ${X}Q${X};done)
fooQfoo barQbar
Run Code Online (Sandbox Code Playgroud)


slm*_*slm 5

我不知道如何只使用花括号来完成这项工作。我也没有看到实现这一目标的方法,所以除非有人比我更聪明,否则我会说这是不可能的。

作为备选

样本数据

$ tree
.
|-- dir1
|   |-- file1
|   `-- file2
`-- dir2
    |-- file1
    `-- file2
Run Code Online (Sandbox Code Playgroud)

例子

$ seq 2 | xargs -i{} echo dir{}/file{}
dir1/file1
dir2/file2
Run Code Online (Sandbox Code Playgroud)

这可以放入这样的命令中:

$ echo $(seq 2 | xargs -i{} echo dir{}/file{})
dir1/file1 dir2/file2
Run Code Online (Sandbox Code Playgroud)

或这个:

$ ls $(seq 2 | xargs -i{} echo dir{}/file{})
dir1/file1  dir2/file2
Run Code Online (Sandbox Code Playgroud)

或这个:

$ ls -l $(seq 2 | xargs -i{} echo dir{}/file{})
-rw-rw-r-- 1 saml saml 0 Sep  2 03:18 dir1/file1
-rw-rw-r-- 1 saml saml 0 Sep  2 03:31 dir2/file2
Run Code Online (Sandbox Code Playgroud)

为什么花括号不能这样做

如果您查看原始示例:

{foo,bar}Q{foo,bar}
Run Code Online (Sandbox Code Playgroud)

其扩展方式如下:

fooQfoo fooQbar barQfoo barQbar
Run Code Online (Sandbox Code Playgroud)

扩展它的机制称为笛卡尔积

例如:

$ echo {A,B}{X,Y,Z}
AX AY AZ BX BY BZ
Run Code Online (Sandbox Code Playgroud)

或这个:

$ echo {M,N}-{A,B}{X,Y,Z}
M-AX M-AY M-AZ M-BX M-BY M-BZ N-AX N-AY N-AZ N-BX N-BY N-BZ
Run Code Online (Sandbox Code Playgroud)

无法创建会导致以下结果的笛卡尔积:

fooQfoo barQbar
Run Code Online (Sandbox Code Playgroud)

你唯一的选择是要么诉诸于这样的诡计:

$ echo dir{1,2}/file{2,1}
dir1/file2 dir1/file1 dir2/file2 dir2/file1
Run Code Online (Sandbox Code Playgroud)

然后将其放入 Bash 数组中:

$ a=(dir{1,2}/file{2,1})
$ echo ${a[@]:1:2}
dir1/file1 dir2/file2
Run Code Online (Sandbox Code Playgroud)

另一种选择是一些“其他方法”,例如我之前在上面讨论过的方法(使用xargs)。

参考