红穆笔记

awk

一種用於文件處理的通用編程語言。 另請參閱:`gawk`

100% 瀏覽器本地處理 0 數據上傳

常用示例

以空格爲分隔符,打印文件每行第五列(也稱作字段)

awk '{print $5}' {{文件名}}

以空格爲分隔符,打印文件包含“foo” 的所有行的第二列

awk '/{{foo}}/ {print $2}' {{文件名}}

以逗號而不是空格作爲分隔符,打印文件每行的最後一列

awk -F ',' '{print $NF}' {{文件名}}

計算文件的第一列數值之和並打印

awk '{s+=$1} END {print s}' {{文件名}}

從第一行開始,每三行打印一行

awk 'NR%3==1' {{文件名}}

根據條件不同,打印不同內容

awk '{if ($1 == "foo") print "Exact match foo"; else if ($1 ~ "bar") print "Partial match bar"; else print "Baz"}' {{文件名}}

打印第 10 列等於指定值的所有行

awk '($10 == 指定值)'

打印第 10 列介於最小值和最大值之間的所有行

awk '($10 >= 最小值 && $10 <= 最大值)'

提示:花括號{{…}}是需要替換的參數(路徑、文件名等);命令只在本機終端執行,本站不保存任何輸入。

英文原文對照

展開英文說明與示例(來源 tldr-pages)

A versatile programming language for working on files. Note: Different implementations of AWK often make this a symlink of their binary. See also: `gawk`. More information

Print the fifth column (a.k.a. field) in a space-separated file

awk '{print $5}' {{path/to/file}}

Print the second column of the lines containing "string1" in a space-separated file

awk '/{{string1}}/ {print $2}' {{path/to/file}}

Print the last column of each line in a file, using a comma (instead of space) as a field separator

awk -F ',' '{print $NF}' {{path/to/file}}

Sum the values in the first column of a file and print the total

awk '{s+=$1} END {print s}' {{path/to/file}}

Print every third line starting from the first line

awk 'NR%3==1' {{path/to/file}}

Print different values based on conditions

awk '{if ($1 == "string1") print "Exact match string1"; else if ($1 ~ "string2") print "Partial match string2"; else print "string3"}' {{path/to/file}}

Print all the lines which the 10th column value is between a min and a max

awk '($10 >= {{min_value}} && $10 <= {{max_value}})' {{path/to/file}}

Print table of users with UID >=1000 with header and formatted output, using colon as separator (`%-20s` mean: 20 left-align string characters, `%6s` means: 6 right-align string characters)

awk 'BEGIN {FS=":";printf "%-20s %6s %25s\n", "Name", "UID", "Shell"} $4 >= 1000 {printf "%-20s %6d %25s\n", $1, $4, $7}' /etc/passwd

命令信息

命令名awk
用途一種用於文件處理的通用編程語言。 另請參閱:`gawk`
適用平臺通用
示例數量8 條
官方文檔https://github.com/onetrueawk/awk
數據來源tldr-pages(CC-BY-4.0)· 社區中文翻譯

常見問題

awk 命令是做什麼的?

一種用於文件處理的通用編程語言。 另請參閱:`gawk`

awk 怎麼用?

頁面按場景列出了8 條常用示例:每條示例先說明用途,再給出可直接複製的完整命令(花括號裏是需要替換的參數)。

awk 最常用的操作是什麼?

以空格爲分隔符,打印文件每行第五列(也稱作字段):awk '{print $5}' {{文件名}}

命令裏的花括號是什麼意思?

花括號{{…}}表示需要替換成你自己的值,例如路徑、文件名;同名參數方括號(如 [-C|--directory])表示可選寫法。