LoginSignup
0
0

More than 5 years have passed since last update.

IDの列を任意の数で区切る

Posted at

Split処理めんどいよね

何か

”データの操作とかする時に対象規模が大きすぎるから一旦任意の数で区切ってWaittime入れてクエリ発行しますよー”

みたいな任意の地点でSplitしろみたいな現象に出くわすことって
サーバサイドなエンジニアやってると何回かあると思うんですけれど
その度に毎回スクリプト書くのもどうなんだということで

「IDのみ羅列されたファイルからN個ずつ区切って出力する」処理をざっくり書いてみました。
穴だらけなのでいつか修正したりするんじゃないでしょうか?

main.go
package main

import (
    "bufio"
    "flag"
    "fmt"
    "os"
    "strconv"
    "strings"
)

var scan = bufio.NewScanner(os.Stdin)

// AllScan is scan and convert text from Stdin datas
func AllScan() []string {
    all := []string{}
    for scan.Scan() {
        all = append(all, scan.Text())
    }
    return all
}

func main() {
    flag.Parse()
    per, err := strconv.Atoi(flag.Arg(0))
    if err != nil {
        per = 500 // default
    }

    data := AllScan()
    repeatCoe := (len(data) / per) + 1 // set repeat count
    for i := 1; i <= repeatCoe; i++ {
        upper := (i * per) - 1
        lowwer := upper - per
        if i == 1 {
            lowwer = 0
        }
        target := []string{}
        if i == repeatCoe {
            target = data[lowwer:]
        } else {
            target = data[lowwer:upper]
        }

        ids := []string{}
        for _, row := range target {
            ids = append(ids, row)
        }
        fmt.Println(strings.Join(ids, ", "))
    }
}

既に書いてて
「AllScan()の時にperで区切る処理持ってくればいいじゃん」
「処理が冗長すぎるのでSlice使わないほうが」
「Shellで絶対簡単に書ける奴」
みたいに思ってますが、まぁいずれ。

テストも書いてないしね。

使い方

雑に

> cat ids.txt | go run main.go 500

などと記述すれば標準出力でIDがドバドバ出てきます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0