LoginSignup
0
1

More than 1 year has passed since last update.

【2022年版】中年から始める awk

Posted at

AWK メモ

基礎書式

  • awk プログラム 入力ファイル
    例:awk '$3 > 100 {print $1, "calc = ", $2 * $3, $0}' data.txt
  • プログラム = パターン {アクション}
    例:'$3 > 100 {print $1, "calc = ", $2 * $3, $0}'
  • サンプル
    % cat << EOF > data.txt
    heredoc> a 1000 0
    heredoc> b 1000 20
    heredoc> c 1000 100
    heredoc> d 800 180
    heredoc> e 1200 0
    heredoc> f 1300 100
    heredoc> EOF
    % awk '$3 > 100 {print $1, "calc = ", $2 * $3, $0}' data.txt
    d 144000
    

パターン

BEGIN, END

  • BEGIN
    構文:BEGIN {文}
    例:BEGIN {print "-----"}
  • END
    構文:END {文}
    例:END {print "-----"}

構文:式 {文}
例:$3 > 100 {print $1, "calc = ", $2 * $3, $0}
例:$1=="c" {print $1, $2 * $3}

正規表現

構文:/正規表現/ {文}
例:/^c+/ {print $1, "calc = ", $2 * $3, $0}
例:/JPN/ {print $1} 行全体にJPNを含む(↓と同一)
例:$0 ~ /JPN/ {print $1} 行全体にJPNを含む
例:$1 ~ /JPN/ {print $1} $1がJPNを含む
例:$1 !~ /JPN/ {print $1} $1がJPNを含まない

複合

  • and
    構文:式 && 式 {文}
    例:$1 == "c" && $3 == 100 {print $1}
  • or
    構文:式 || 式 {文}
    例:$3 == 0 || $3 == 100 {print $1}

範囲

構文:パターン1, パターン2 {文}
例:/JPN/, /USSR/ {print $1}JPNからUSSRまでの範囲が該当(USSRが出てこなければ最終行まで全選択

組込変数

  • ARGC
    コマンド行引数の数
  • ARGV
    コマンド行引数の配列
  • FILENAME
    ファイル名、新しいファイルが読まれるたびに設定される
  • FNR
    現在までに読み込んだ現在のファイルの行数、現在のファイルのレコード番号
  • FS
    列の区切り文字
  • NF
    現在のレコードの列数
  • NR
    現在までに読み込んだ行数
  • OFMT
  • OFS
  • ORS
  • RLENGTH
  • RS
    行の区切り文字、入力レコードの区切文字
  • RSTART
  • SUBSEP

組込算術関数

  • atan2(y, x)
  • cos(x)
  • exp(x)
  • int(x)
  • log(x)
  • rand()
  • sin(x)
  • sqrt(x)
  • srand(x)

組込文字列関数

  • gsub(r, s)
  • gsub(r, s, t)
  • index(s, t)
  • length(s)
  • match(s, r)
  • split(s, a)
  • split(s, a, fs)
  • sprintf(書式, 式)
  • sub(r, s)
  • sub(r, s, t)
  • substr(s, p)
  • substr(s, p, n)

アクション

  • print 式
  • print (書式, 式)

制御文

  • if (式) 文
  • if (式) 文 else 文
  • while (式) 文
  • for (式; 式; 式) 文
  • for (変数 in 配列) 文
  • do 文 while (式)
  • break
  • continue
  • next
  • exit
  • exit 式
  • {文}

配列

  • split
  • delete
  • pop

ユーザ定義関数

  • function 関数名(引数) {文}

出力

  • print
  • printf
  • close
  • system

print文

ファイル

パイプ

入力

区切り

複行

getline関数

system関数

データ変換

データ検証

Bndle, unbundle

複行

0
1
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
1