[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 !!!
[Corazon@rocky8:~]$ ll a -rw-rw-r--. 1 Corazon Corazon 0 Feb 19 13:31 a [Corazon@rocky8:~]$ su Password: [root@rocky8:Corazon]# chown Cora a [root@rocky8:Corazon]# ll a -rw-rw-r--. 1 Cora Corazon 0 Feb 19 13:31 a
修改文件所属组:chgrp
1 2 3 4 5 6 7
[root@rocky8:Corazon]# ll a -rw-rw-r--. 1 Cora Corazon 0 Feb 19 13:31 a [root@rocky8:Corazon]# ll a -rw-rw-r--. 1 Cora Corazon 0 Feb 19 13:31 a [root@rocky8:Corazon]# chgrp Cora a [root@rocky8:Corazon]# ll a -rw-rw-r--. 1 Cora Cora 0 Feb 19 13:31 a
1、查看当前操作系统内核信息 uname -a $ uname -a zhang@rocky9:~$ uname -a Linux rocky9 5.14.0-284.11.1.el9_2.x86_64 #1 SMP PREEMPT_DYNAMIC Tue May 917:09:15 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
2、查看当前操作系统版本信息 cat /proc/version $ cat /proc/version Linux version 3.10.0-693.21.1.el7.x86_64 (builder@kbuilder.dev.centos.org) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) ) #1 SMP Wed Mar 7 19:03:37 UTC 2018
3、查看当前操作系统发行版信息 cat /etc/issue 或 cat /etc/redhat-release $ cat /etc/issue \S Kernel \r on an \m
$ cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core)
4、查看cpu相关信息,包括型号、主频、内核信息等 cat /proc/cpuinfo $ cat /proc/cpuinfo processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 45 model name : Intel® Xeon® CPU E5-2660 0 @ 2.20GHz stepping : 7 microcode : 0xffffffff cpu MHz : 2199.998 cache size : 20480 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 2 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology eagerfpu pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 popcnt aes xsave avx hypervisor lahf_lm xsaveopt bogomips : 4399.99 clflush size : 64 cache_alignment : 64 address sizes : 44 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 45 model name : Intel® Xeon® CPU E5-2660 0 @ 2.20GHz stepping : 7 microcode : 0xffffffff cpu MHz : 2199.998 cache size : 20480 KB physical id : 0 siblings : 2 core id : 1 cpu cores : 2 apicid : 1 initial apicid : 1 fpu : yes fpu_exception : yes cpuid level : 13 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology eagerfpu pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 popcnt aes xsave avx hypervisor lahf_lm xsaveopt bogomips : 4399.99 clflush size : 64 cache_alignment : 64 address sizes : 44 bits physical, 48 bits virtual power management:
5、列出所有版本信息 lsb_release -a $ lsb_release -a -bash: lsb_release: command not found 出现command not found说明没安装lsb_realease,可以执行命令yum install -y redhat-lsb安装lsb_realease,安装完成后,版本信息如下: $ lsb_release -a LSB Version: :core-4.1-amd64:core-4.1-noarch:cxx-4.1-amd64:cxx-4.1-noarch:desktop-4.1-amd64:desktop-4.1-noarch:languages-4.1-amd64:languages-4.1-noarch:printing-4.1-amd64:printing-4.1-noarch Distributor ID: CentOS Description: CentOS Linux release 7.4.1708 (Core) Release: 7.4.1708 Codename: Core
Shell是用户与Linux系统之间的接口。Linux的Shell有许多种,每种都有不同的特点。常用的有sh(Bourne Shell), csh(C Shell), ksh(Korn Shell), tcsh(TENEX/TOPS-20 type C Shell), bash(Bourne Again Shell)等。