字符和数字的所有可能组合

ard*_*evd 20 bash

所以我想生成可以组成 5 个字符串的大小写字符和数字的所有可能组合。

可能性:a..z、A..Z 和 0..9。

在 bash 中是否有任何优雅的方法可以做到这一点?

PSk*_*cik 18

这是一个将所需长度作为参数的 bash 解决方案(您可以permute 5在您的情况下这样做):

#!/bin/bash
charset=({a..z} {A..Z} {0..9})
permute(){
  (($1 == 0)) && { echo "$2"; return; }
  for char in "${charset[@]}"
  do
    permute "$((${1} - 1 ))" "$2$char"
  done
}
permute "$1"
Run Code Online (Sandbox Code Playgroud)

不过,它的速度很慢。我敢推荐C吗?https://youtu.be/H4YRPdRXKFs?t=18s

#include <stdio.h>

//global variables and magic numbers are the basis of good programming
const char* charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char buffer[50];

void permute(int level) {
  const char* charset_ptr = charset;
  if (level == -1){
    puts(buffer);
  } else {
    while(buffer[level] = *charset_ptr++) {
      permute(level - 1);
    }
  }
}

int main(int argc, char **argv)
{
  int length;
  sscanf(argv[1], "%d", &length); 

  //Must provide length (integer < sizeof(buffer)==50) as first arg;
  //It will crash and burn otherwise  

  buffer[length] = '\0';
  permute(length - 1);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行:

make CFLAGS=-O3 permute && time ./permute 5 >/dev/null #about 20s on my PC
Run Code Online (Sandbox Code Playgroud)

高级语言在蛮力方面很糟糕(这基本上就是你正在做的事情)。


Sté*_*las 11

在 中bash,您可以尝试:

printf "%s\n" {{a..z},{A..Z},{0..9}}{{a..z},{A..Z},{0..9}}{{a..z},{A..Z},{0..9}}{{a..z},{A..Z},{0..9}}{{a..z},{A..Z},{0..9}}
Run Code Online (Sandbox Code Playgroud)

但这会花费很长时间并耗尽你所有的记忆。最好是使用另一种工具,如perl

perl -le '@c = ("A".."Z","a".."z",0..9);
          for $a (@c){for $b(@c){for $c(@c){for $d(@c){for $e(@c){
            print "$a$b$c$d$e"}}}}}'
Run Code Online (Sandbox Code Playgroud)

请注意,这是 6 x 62 5个字节,因此是 5,496,796,992。

您可以在 中执行相同的循环bash,但bash作为西部最慢的 shell,这将需要几个小时:

export LC_ALL=C # seems to improve performance by about 10%
shopt -s xpg_echo # 2% gain (against my expectations)
set {a..z} {A..Z} {0..9}
for a do for b do for c do for d do for e do
  echo "$a$b$c$d$e"
done; done; done; done; done
Run Code Online (Sandbox Code Playgroud)

(在我的系统上,输出速度为 700 kiB/s,而perl同等条件下的输出速度为 20MiB/s )。

  • @Hellreaver,它们都写入一个文件(写入标准输出,任何打开的文件;如果在终端中运行,则是像`/dev/pts/something` 这样的设备文件;您可以使用 shell 重定向操作符更改它),不是内存,但第一个在输出之前在内存中构建整个输出(到在标准输出上打开的文件)。 (3认同)

G-M*_*ca' 7

这是一种纯粹在 bash 中完成而无需 chomp 5 GB 内存的方法:

for c1 in {A..Z} {a..z} {0..9}
do
    for c2 in {A..Z} {a..z} {0..9}
    do
        for c3 in {A..Z} {a..z} {0..9}
        do
            for c4 in {A..Z} {a..z} {0..9}
            do
                for c5 in {A..Z} {a..z} {0..9}
                do
                    printf "%s\n" "$c1$c2$c3$c4$c5"
                done
            done
        done
    done
done
Run Code Online (Sandbox Code Playgroud)


use*_*456 5

您可以使用crunch(至少在 Kali 发行版上可用)。

crunch 5 5 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
Run Code Online (Sandbox Code Playgroud)