Awk 内置函数

Awk 提供了丰富的 数值计算字符串处理数组操作系统调用 函数。本章节详细介绍 Awk 的常见内置函数。


1. 数值计算函数(Numerical Functions)

这些函数用于数值运算,参数和返回值都是数值。

函数 说明 示例 输出
int(x) 取整(向零取整) int(-3.9) -3
sqrt(x) 平方根 sqrt(25) 5
exp(x) 指数函数 e^x exp(1) 2.718...
log(x) 自然对数 ln(x) log(10) 2.302...
sin(x) 正弦(弧度制) sin(3.14/2) 1
cos(x) 余弦(弧度制) cos(0) 1
atan2(y,x) 反正切(返回 y/x 的角度,弧度制) atan2(1,1) 0.785...
rand() 生成 [0,1) 之间的随机数 rand() 0.847...
srand([x]) 设置随机数种子(x 可选) srand(123) 返回上一次的种子

示例:随机数

BEGIN {
    srand()  # 用当前时间作为种子
    print rand()   # 生成一个随机数
}

2. 字符串处理函数(String Functions)

这些函数用于字符串操作,包括查找、替换、格式化等。

函数 说明 示例 输出
length([s]) 获取字符串长度(默认为 $0 length("hello") 5
substr(s, m [,n]) 截取子字符串 substr("awk",2,2) "wk"
split(s, A [,regexp]) regexp 分割 s,存入数组 A split("a:b:c", arr, ":") arr[1]="a", arr[2]="b", arr[3]="c"
sprintf(format, ...) 格式化字符串 sprintf("%0.2f", 3.14159) "3.14"
gsub(regexp, s [,t]) 全局替换 regexps(修改 t,默认为 $0 gsub(/a/, "A", "banana") "bAnAnA"
sub(regexp, s [,t]) 替换 regexp 的第一个匹配 sub(/a/, "A", "banana") "bAnana"
index(s, t) 返回 ts 中的起始位置(找不到返回 0 index("hahaha", "ah") 2
match(s, regexp) 返回 regexps 中的匹配位置 match("banana", /a+/) 2
tolower(s) 转换为小写 tolower("HELLO") "hello"
toupper(s) 转换为大写 toupper("hello") "HELLO"

示例:字符串拆分

BEGIN {
    str = "apple,banana,grape"
    split(str, fruits, ",")
    print fruits[1], fruits[2], fruits[3]  # 输出 "apple banana grape"
}

示例:替换字符串

BEGIN {
    text = "apple apple apple"
    gsub(/apple/, "banana", text)
    print text  # 输出 "banana banana banana"
}

3. 系统函数(System Function)

函数 说明
system(s) 运行 shell 命令 s

示例:列出当前目录

BEGIN { system("ls -l") }

4. GNU Awk 扩展函数

gawk 提供了扩展的字符串和数组函数

4.1 gensub()

gensub(regexp, s, h [, t])
替换 t 中的第 hregexp 匹配项,返回新字符串(不会修改原字符串)。

示例 输出
gensub(/o/, "O", 3, "cooperation") "cooperatiOn"
gensub(/o/, "O", "g", "cooperation") "cOOperatiOn"
gensub(/(o+)(p+)/, "<[\\1](\\2)>", "g", "I oppose cooperation") "I <[o](pp)>ose c<[oo](p)>eration"

4.2 patsplit()

patsplit(s, A [,regexp [,B]])
类似 split(),但 regexp 匹配的是模式(pattern)而不是分隔符(separator)

示例 说明
patsplit("abc123def456", arr, /[a-z]+/) arr[1]="abc", arr[2]="def"

5. 数组函数(Array Functions,GNU Awk 扩展)

gawk 提供了一些处理数组的函数。

函数 说明
length(A) 返回数组 A 的大小
asort(A[,B]) 按值排序 A(如果提供 B,则将 A 复制到 B 并排序)
asorti(A[,B]) 按索引排序 A(如果提供 B,则 BA 的排序索引为值)

示例:按值排序

BEGIN {
    arr[1] = 30
    arr[2] = 10
    arr[3] = 20

    asort(arr, sorted)

    for (i in sorted)
        print sorted[i]  # 输出 10 20 30
}

示例:按索引排序

BEGIN {
    arr["c"] = 3
    arr["a"] = 1
    arr["b"] = 2

    asorti(arr, sorted)

    for (i in sorted)
        print sorted[i], arr[sorted[i]]  # 输出 a 1  b 2  c 3
}

总结

类别 常用函数
数值计算 int(), sqrt(), log(), rand(), srand()
字符串操作 length(), substr(), split(), gsub(), toupper(), tolower()
系统函数 system()
GNU Awk 扩展 gensub(), patsplit(), asort(), asorti()

练习

  1. 提取文件扩展名

    awk '{ print substr($0, index($0, ".")+1) }' filenames.txt
    

    输入 filenames.txt

    document.pdf
    report.docx
    image.png
    

    输出

    pdf
    docx
    png
    
  2. 查找最长单词

    awk '{ for (i=1; i<=NF; i++) if (length($i) > max) { max = length($i); word = $i } } END { print word }' words.txt
    

    输入 words.txt

    awk is powerful scripting language
    

    输出

    powerful
    

在下一章,我们将学习 如何编写自定义函数(User-Defined Functions) 🚀

Last modified: Thursday, 30 January 2025, 1:09 AM