bash排列单词列表



我有这样的短语:

The quick brown $UNKNOWN1 jumps over the $UNKNOWN2 dog

我有这样的世界主义:

me
black
lazy
swan
dog
word
sky
fox
nothing
you

如何将列表中的列表置于bash中,以使所有排列如下:

The quick brown you jumps over the nothing dog

The quick brown fox jumps over the lazy dog

等等,所有排列。我尝试了一些循环,但被卡住了,因为我认为我需要在循环(嵌套循环)内进行一些循环。类似:

for i in `cat wordlist.txt`;
  do echo "The quick brown $i jumps over the $UNKNOWN2 dog";
done

编辑:

我认为这就是:

#!/bin/bash
for i in `cat wordlist.txt`
  do
    for a in `cat wordlist.txt`
      do
        echo "The quick brown $i jumps over the $a dog"
    done
done

只是为了娱乐, gnu Parallel 也很好地置于排列:

parallel echo The quick brown {1} jumps over the {2} dog :::: wordlist.txt :::: wordlist.txt

或相同,但省略了两个单词相同的行:

parallel 'bash -c "[ {1} != {2} ] && echo The quick brown {1} jumps over the {2} dog"' :::: wordlist.txt wordlist.txt

我认为我需要在循环内进行一些循环。

你是对的:

for i in $(cat wordlist.txt)
do
  for j in $(cat wordlist.txt)
  do
    echo "The quick brown $i jumps over the $j dog"
  done
done

您可以选择避免使用$i = $j

for i in $(cat wordlist.txt); do
  for j in $(cat wordlist.txt); do
    if [ "$i" != "$j" ]; then
      echo "The quick brown $i jumps over the $j dog"
    fi
  done
done

也有一个没有循环的hacky替代方案:

printf "The quick brown %s jumps over the %s dog.n" $(join -j 2 words words)

在这种情况下, join与自身创建单词列表的笛卡尔产品。结果是单词列表。这些单词中的每个单词都作为参数传递给printf
printf打印句子,用列表中的下一个单词代替%s。在打印一次句子后,它仍然没有读单词,并继续直到打印所有单词。

好处:

  • 较短的程序
  • 比循环快

缺点(与for i in $(cat wordlist)完全相同)

  • 可能会因最大而失败。参数数量。
  • 如果单词列表包含*?这些可能会通过bash扩展。
  • 单词列表中的单词必须是真实的单词,不允许空格。

最新更新