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?

【AWK】特定のフィールドの値を取得する方法

Posted at

特定のフィールドの値を取得する方法

以下のようなコマンドを実行すると、sample.txt内の空白をフィールドの区切り文字として2番目のフィールドの値を取得できます。

awk '{print $2}' sample.txt
  • $1:1番目のフィールド
  • $2:2番目のフィールド
  • $3:3番目のフィールド
  • 以降同様

以下のようなサンプルデータを含むファイル data.txt を用意します。

data.txt
Alice 25 Engineer
Bob 30 Designer
Charlie 22 Developer

各行の2番目のフィールドを取得

次のコマンドを実行して、各行の2番目のフィールド(年齢)を取得します。

$ awk '{print $2}' data.txt
25
30
22
  • awk:AWKコマンドを呼び出す
  • '{print $2}':各行の2番目のフィールドを出力する
  • data.txt:処理対象のファイル名

複数フィールドの取得

複数のフィールドを取得することも可能です。例えば、名前と年齢を取得する場合は次のようにします。

$ awk '{print $1, $2}' data.txt
Alice 25
Bob 30
Charlie 22

別の区切り文字を使用する

もしデータがカンマで区切られている場合、-Fオプションを使用して区切り文字を指定できます。

data.txt
Alice,25,Engineer
Bob,30,Designer
Charlie,22,Developer
$ awk -F',' '{print $2}' data.txt
25
30
22
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?