プログラミング

Bashで乱数のランダムな横n文字x縦n文字のテキストデータを生成する

Linuxパソコン・サーバーのコマンドラインからBashで乱数のランダムな横n文字x縦n文字のテキストデータを生成する方法について紹介します。

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_27c993f8-6efa-4bc8-acc1-f7aee93ac155.png

5文字x5文字 合計25文字のランダムな文字キャラクターで構成されたテキストデータを生成する例

yuis ASUS /mnt/c/pg$ gentext 5 5 random
AsVDT
iCPZi
Ihlv8
NVwc0
TofvP

乱数にする必要がない場合は第三引数を空欄または任意の文字で指定で同じ文字でテキストデータが出力されます。

yuis ASUS /mnt/c/pg$ gentext 5 5
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

生成されたデータをファイルに出力したい場合は通常通りパイプします。

yuis ASUS /mnt/c/pg$ gentext 5 5 random > tmp.txt

以下コードです。


gentext02(){
  : <<< '
  generate a large size of text contents.

  e.g. gentext02 [width] [height] [char]
  e.g. gentext02 100 100 Z
  e.g. gentext02 100 100 random > tmp.txt

  i.e. check how long time fzf takes against to a large of text contents.
    tmpdird
    push gentext02 20 50000 random > tmp.txt
    cat tmp.txt | fzf
  '

  for i in $(seq "${2:-10}") ; do
    # printf "${3:-X}%.0s" {1..${1:-10}} ; printf '\n'

      [[ "${3}" =~ rand|random ]] && {
        # printf "$( randsel {a..z} )%.0s" $( eval "echo {1..${1:-10}}" ) ; printf '\n'
        random ${1:-10}
      } || {
        printf "${3:-X}%.0s" $( eval "echo {1..${1:-10}}" ) ; printf '\n'
      }

  done

}

alias gentext="gentext02"
random(){
  ARG1=${1:-32}
  # cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w $1 | head -n 1
  cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w $ARG1 | head -n 1
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です