awk内建函数之字符串函数

index(原字符串,匹配字符串)正则表达式

length(字符串)数组

match(原字符串,正则表达式)bash

split(原字符串,数组名称,分隔字符)ide

sprintf(格式字符串,项1,项2,...)函数

sub(正则,替换的新字符串,原字符串)字符串

gsub(正则表达式,替换的新字符串,原字符串 )it

substr(字符串,起始位置,截取长度)io

tolower(字符串)class

toupper(字符串)awk




1. index(原字符串,匹配字符串)

若“原字符串”含有“匹配字符串”,则返回其在原字符串中第一次出现的位置,若不曾出现则返回0。

例 :

# awk 'BEGIN {
print index("33080801030","0");
print index("3380801030","0");
}'
3
4

2.length(字符串)

返回参数“字符串”的长度。

范例:

# awk 'BEGIN {print length("chenss")}'
6

3.match(原字符串,正则表达式)

awk会在“原字符串”中匹配合乎“正则表达式”的字符串.若匹配到的字符串有多个, 则以“原字符串”中最左侧的字符串为准。

若是匹配到字符串后,match函数则会返回”正则表达式“匹配到的字符串的位置。

并设定RSTART变量为”匹配字符串“在”原字符串“中的位置,若未匹配到则等于0 ;

设定RLEGTH变量为匹配的字符串的长度, 若未匹配则等于-1。

范例:

# awk 'BEGIN {
match("The best preparation for tomorrow is doing your best today",/best/);
print RSTART;
print RLENGTH;
}'
5
4

范例:

# awk 'BEGIN {
match("The best preparation for tomorrow is doing your best today",/chenss/);
print RSTART;
print RLENGTH;
}'
0
-1

4.split(原字符串,数组名称,分隔字符)

awk将依所指定的“分隔字符”来分隔“原字符串”,并以指定的“数组名称”记录各个被分隔的字段。若是第三个参数没有提供,awk就默认使用当前FS值。

范例:

# awk 'BEGIN {
T="The best-preparation-for-tomorrow is doing your best-today";
split(T,Arry,"-");
print Arry[2];
split(T,Arry);
print Arry[2];
}'
preparation
best-preparation-for-tomorrow

5.sprintf(格式字符串,项1,项2,...)

用法与printf()相似. 不一样的是sprintf()将打印出的结果当成一个字符串返回。通常用sprintf()来格式化字符串。

范例:

# awk 'BEGIN {
print sprintf("%.2f",88);
print sprintf("%.x",15);
}'
88.00
f

6.sub(正则表达式,新字符串,原字符串)

sub( )将“原字符串”中第一个匹配“正则表达式”的字符串替换成“新字符串”,"新字符串"中可用"&"来追加字符串 ;当第二个参数为空字符串("")时,sub()将执行的是去除“正则表达式”所匹配的最左侧字符串。

sub( )中第三个参数(原字符串)若未指定,则其预设值为$0.

范例:

# awk 'BEGIN {
T="The best-preparation-for-tomorrow is doing your best-today";
sub(/-/,".",T);
print T;
sub(/today/,"&!",T);
print T;
sub(/-/,"",T);
print T
}'
The best.preparation-for-tomorrow is doing your best-today
The best.preparation-for-tomorrow is doing your best-today!
The best.preparationfor-tomorrow is doing your best-today!

经过 sub() 与 match() 的配合使用,可取出全部匹配的字符串。

范例:

# awk 'BEGIN {
T="p12-p34 p56-p78";
while(match(T,/[0-9]+/) > 0)
{
print substr(T,RSTART,RLENGTH);
sub(/[0-9]+/,"",T);
}
}'
12
34
56
78

7.gsub(正则表达式,替换的新字符串,原字符串 )

用法与sub()函数同样, 惟一不一样点是 gsub函数使全部被正则表达式匹配的字符串都发生替换

范例:

# awk 'BEGIN {
T="The best-preparation-for-tomorrow is doing your best-today";
gsub(/-/,".",T);
print T;
gsub(/^/,"&BEGIN: ",T);
print T;
gsub(/best/,"&+",T);
print T
}'

8.substr(字符串,起始位置,截取长度)

返回从起始位置起,指定长度的字符串;若未指定长度, 则返回从起始位置到字符串末尾的子字符串。

范例:

# awk 'BEGIN {
T="The best-preparation-for-tomorrow is doing your best-today";
print substr(T,4,17);
print substr(T,4);
}'
 best-preparation
 best-preparation-for-tomorrow is doing your best-today

9.tolower(字符串)

参数“字符串”中的大写字母替换成小写

范例:

# awk 'BEGIN {print tolower("AbCd")}'
abcd

10.toupper(字符串)

范例:

参数“字符串”中的小写字母替换成大写

# awk 'BEGIN {print toupper("AbCd")}'
ABCD
相关文章
相关标签/搜索