0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SadServers学習メモ #5】使ったコマンドまとめ(awk)

Posted at

初めに

Linuxの学習目的でSadServersを始めました。
備忘のために使用したコマンドをアウトプットします。

SadServersとは

Linuxの学習サイト。
架空のサーバを題材とし、その管理者となって与えられた依頼をこなしていく。
実際にコマンドを使って作業をすることで、実践的なスキルが身につくことが期待できる。

今回のお題

タイトル

"Lhasa": Easy Math

詳細

  • ある数列の平均を求める
  • 数列は以下のように2列になっており、2列目の値の平均を求める
  • 少数第三位を切り捨て、少数第二位の値で答える
scores.txt
1 7.4
2 0.4
3 1.6
4 6.2
5 7.6
6 7.7
...

作業の流れ

  • 2列目を抽出し、母数をカウントしておく
  • 抽出した数列の合計値を求める
  • 平均を求める
  • 少数を切り捨てる

使ったコマンド

awkコマンド

おなじみのawkコマンドを使います。

二列目の抽出 & 合計取得 $ 母数のカウント

  • 変数を扱うことができる
  • セミコロンをつけることで複数の処理を実行できる
$ awk '{s += $2; count++}

平均を求める & 切り捨て

  • 合計÷母数で平均を求める
  • int(ave * 100)/100で少数第三位を切り捨てた値を取得
  • 最小桁数が0の場合でも省略されないよう、printf "%.2f\n"で出力形式を指定
{ ave = s / count; trancation = int(ave*100)/100; printf "%.2f\n", trancation }

ENDでつなげる

$ awk '{s += $2; count++} END { ave = s / count; trancation = int(ave*100)/100; printf "%.2f\n", trancation }' scores.txt

終わりに

awk便利ですね。毎回助けられてます。
最初はただ列を抽出するだけのコマンドかと思ってましたが、ちょっとした計算もできるのが便利でよいです。
他の問題でも使えると思うので、また学んだらアウトプットします。

ここまでご覧いただきありがとうございました!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?