一、函数
1 系统函数
1 basename
1)基本语法
basename [string / pathname] [suffix] (功能描述:basename 命令会删掉所有的前 缀包括最后一个(‘/’)字符,然后将字符串显示出来。
basename 可以理解为取路径里的文件名称 选项:
suffix 为后缀,如果 suffix 被指定了,basename 会将 pathname 或 string 中的 suffix 去掉。
2)案例实操
截取该/home/atguigu/banzhang.txt 路径的文件名称。
[atguigu@hadoop101 shells]$ basename /home/atguigu/banzhang.txt
banzhang.txt
[atguigu@hadoop101 shells]$ basename /home/atguigu/banzhang.txt .txt
banzhang
2 dirname
1)基本语法
dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名 (非目录的部分),然后返回剩下的路径(目录的部分))
dirname 可以理解为取文件路径的绝对路径名称
2)案例实操 获取 banzhang.txt 文件的路径。
[atguigu@hadoop101 ~]$ dirname /home/atguigu/banzhang.txt
/home/atguigu
2 自定义函数
1)基本语法
[ function ] funname[()]
{
Action;
[return int;]
}
2)经验技巧
(1)必须在调用函数地方之前,先声明函数,shell 脚本是逐行运行。不会像其它语言一 样先编译。
(2)函数返回值,只能通过$?系统变量获得,可以显示加:return 返回,如果不加,将 以最后一条命令运行结果,作为返回值。return 后跟数值 n(0-255)
3)案例实操 计算两个输入参数的和。
[atguigu@hadoop101 shells]$ touch fun.sh [atguigu@hadoop101 shells]$ vim fun.sh #!/bin/bash function sum() { s=0 s=$[$1+$2] echo "$s" }read -p "Please input the number1: " n1; read -p "Please input the number2: " n2; sum $n1 $n2; [atguigu@hadoop101 shells]$ chmod 777 fun.sh [atguigu@hadoop101 shells]$ ./fun.sh Please input the number1: 2 Please input the number2: 5 7
二、正则表达式入门
正则表达式使用单个字符串来描述、匹配一系列符合某个语法规则的字符串。在很多文 本编辑器里,正则表达式通常被用来检索、替换那些符合某个模式的文本。在 Linux 中,grep, sed,awk 等文本处理工具都支持通过正则表达式进行模式匹配。
1 常规匹配
一串不包含特殊字符的正则表达式匹配它自己,例如:
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep atguigu
就会匹配所有包含 atguigu 的行。
2 常用特殊字符
1)特殊字符:^
^ 匹配一行的开头,例如:
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep ^a
会匹配出所有以 a 开头的行
2)特殊字符:$
$ 匹配一行的结束,例如
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep t$
会匹配出所有以 t 结尾的行
思考:^$ 匹配什么?
3)特殊字符:.
. 匹配一个任意的字符,例如
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep r..t
会匹配包含 rabt,rbbt,rxdt,root 等的所有行
4)特殊字符:*
- 不单独使用,他和上一个字符连用,表示匹配上一个字符 0 次或多次,例如
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep ro*t
会匹配 rt, rot, root, rooot, roooot 等所有行
思考:.* 匹配什么?
5)字符区间(中括号):[ ]
[ ] 表示匹配某个范围内的一个字符,例如
[6,8]------匹配 6 或者 8
[0-9]------匹配一个 0-9 的数字
[0-9]*------匹配任意长度的数字字符串
[a-z]------匹配一个 a-z 之间的字符
[a-z]* ------匹配任意长度的字母字符串
[a-c, e-f]-匹配 a-c 或者 e-f 之间的任意字符
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep r[a,b,c]*t
会匹配 rt,rat, rbt, rabt, rbact,rabccbaaacbt 等等所有行
6)特殊字符:\
\ 表示转义,并不会单独使用。由于所有特殊字符都有其特定匹配模式,当我们想匹配 某一特殊字符本身时(例如,我想找出所有包含 ‘$’ 的行),就会碰到困难。此时我们就要 将转义字符和特殊字符连用,来表示特殊字符本身,例如
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep ‘a\$b’
就会匹配所有包含 a$b 的行。注意需要使用单引号将表达式引起来。
例子:匹配手机号
[root@hadoop100 scripts]# echo "13569857469" | grep ^1[34578][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
13569857469
[root@hadoop100 scripts]# echo "13569857469" | grep -E ^1[34578][0-9]{9}$ #-E是允许使用扩展正则表达式
13569857469
[root@hadoop100 scripts]#