LoginSignup
63
66

More than 5 years have passed since last update.

awkへシェルスクリプトの変数を渡す

Posted at

awkの基本形

$ awk 'パターン {アクション}' ファイル名

シェル変数として渡したいのは、「パターン」もしくは「アクション」です。

1. パターンをシェル変数として渡す場合

/'"${shell_pattern}"'/のように、変数をシングル、ダブル、<シェル変数>、ダブル、シングルクォーテーションで括ればよい。

2. アクション(パターン以外)にシェル変数を渡す場合

-vオプションを使う
-v awk_action_val="${shell_action_val}"


1,2.を組み合わせたサンプル

captain.csv
Taniguchi Third,Pitcher
Marui Second
Igarashi Third,Pitcher
Kondo Pitcher
awkval_test.sh
#!/bin/bash

shell_file="$1"
shell_pattern="$2"

awk -v awk_file="${shell_file}" '/'"${shell_pattern}"'/ {print  awk_file "(" NR "):" $0}' ${shell_file}

実行例

$ ./awkval_test.sh captain.csv Marui
captain.csv(2):Marui Second

メモ

  • シェル変数を渡すオプション--assignはMacのawkだと使えない。GNU Awkは--assignが使える
  • NR:行番号、$0:行全体
63
66
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
63
66