shell语句:awk基本用法
测试文本0519.txt的内容:
1. zhangsan 6y man
2. lisi 11y woman
3. wangwu 21y man
4. zhouwu 36y man
Faillure is the mother of success.
*********1024******
awk命令:
1. 基本用法:
1.1 其中options代表参数,单引号中的内容代表要执行的命令,filename代表文件名
awk [options] '{[pattern] commands}' {filenames}
1.2 从标准输入,按空格分割字符串并输出
echo 'this is my school' | awk 'BEGIN{FS=" "}{print $1,$2,$3}'
(等同于:'echo 'this is my school' | awk '{print $1,$2,$3}
),默认按空格分割
1.3 输出小于1024字节的文件或文件夹
ll | awk '{if($5 < 1024) print $0}'
1.4 从文件0519.txt按.分割每行,输出第一个、第二个字符串
awk 'BEGIN{FS="."}{print $1,$2}' ./0519.txt
(等同于:awk -F. '{print $1,$2}' ./0519.txt
)
2. 变量
2.1 变量NF代表该行有多少个字段,因此$NF代表最后一个字段
从文件0519.txt按.分割每行,输出倒数第二个、倒数一个字符串
awk 'BEGIN{FS=" "}{print$NF-1, $NF}' ./0519.txt
2.2 变量NR代表当前处理的是第几行
输出文件的行数
awk -F. '{print NR}' ./0519.txt
3. 函数
toupper: 转为大写
tolowe: :转为小写
length: 返回字符串长度
substr: 返回字符子串
sin(): 正弦
sqrt(): 平方根
rand(): 随机数
3.1 从文件0519.txt默认按空格分割每行,第一个、第二个字符串转为大写,并写入文件0519_transfer.txt
awk '{print toupper($1), toupper($2) >> "0519_transfer.txt"}' ./0519.txt
3.2 输出第2个字段第1~3个字符串
awk '{print substr($2,1,3)}' ./0519.txt
3.3 输出第2个字段第2个至最后个字符串
awk '{print substr($2,2)}' ./0519.txt
3.4 输出第1个字段按-分割后的第2个字段
echo "ceph_12.2.1.centos.x86_64.tar.gz-2021-10-08-08"|awk '{split($1, arr, "-"); print arr[2]}'
4. 条件
4.1 awk允许指定输出条件,输出条件要写在动作前面
4.2 输出包含man的行
awk -F. '/man/{print $0}' ./0519.txt
4.3 输出奇数行
awk 'NR%2==1{print $0}' ./0519.txt
4.4 输出第二个字段为zhangsan或者lisi的行
awk '$2=="zhangsan"||$2=="lisi"{print $0}' ./0519.txt
5. if语句
用于编写复杂的语句
输出第四个字段为man的行,否则输出"-"
awk '{if($4=="man")print $0; else{print "-"}}' ./0519.txt