12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルで文字数を数える(あるいは、Rubyにおけるシェル芸)

Last updated at Posted at 2014-05-07

文字数、単純に数えようとすると

$ echo '隣の客はよく柿食う客だ' | wc -c
      34

バイト数になる。半角全角入り乱れたりするとよくわからなくなる。

Rubyという便利なコマンドを挟んでみる。

$ echo '隣の客はよく柿食う客だ' | ruby -pe 'gsub /./, "\\\\0 "' | wc -w
      11

良さそう。

$ ruby \
    -p \ # 標準入力を一行ずつ回して、結果をプリントする(sed風)
    -e \ # 後ろに伴うスクリプトを実行する
    'gsub /./, "\\\\0 "'
    # Kernel#gsub は、一行ずつ回した内容に対してString#gsubを実行するメソッド。
    # マルチバイトに対応しつつ一文字ごとに半角スペースを挿入する

注意

http://qiita.com/udzura/items/3f141ee674cd5e619ae0#comment-64fee1ff14f7cfdec77b の影響で、「\\0」の「0」を全角に直しています

追記

シェル芸関係者に捕捉され、補足されました。

$ echo -n '隣の客はよく柿食う客だ' | wc -m

これはスマートですが、やり方は色々あるというお言葉も頂戴したので各位頑張りましょう!!!!

12
10
7

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
12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?