Exercises for sed and awk
Use sed to print out the IP address:
[root@Srv02 ~] # ifconfig eth0 | grep Mask | sed's / ^. * dr://g' | sed 's/Bc.*$//g'192.168.1.223 [root@Srv02 ~] # ifconfig eth0 | grep Mask | sed-n's / ^. * dr:\ (. *\) Bc.*$/\ 1/gp'192.168.1.223
Awk print IP:
[root@Srv02 ~] # ifconfig eth0 | grep Mask | awk'{print $2}'| awk-F:'{print $2} '192.168.1.223 [root@Srv02 ~] # ifconfig eth0 | grep Mask | awk-F [:\]' {print $13} '192.168.1.223
Specify the delimiter using awk internal variables:
[root@Srv02 ~] # ifconfig eth0 | grep Mask | awk 'BEGIN {FS= "[:\]"} {print $13}' 192.168.1.223
In the print / etc/passwd file, $1 is the two lines of weblogic and tomcat (using the judgment statement):
[root@Srv02 ~] # more / etc/passwd | awk-F:'{if ($1 million = "weblogic" | | $1 million = "tomcat") print $0} 'weblogic:x:501:503::/home/weblogic:/bin/bashtomcat:x:502:504::/home/tomcat:/bin/bash
Using ~ here has the same effect:
[root@Srv02 ~] # more / etc/passwd | awk-F:'{if ($1 ~ "weblogic" | | $1 ~ "tomcat") print $0} 'weblogic:x:501:503::/home/weblogic:/bin/bashtomcat:x:502:504::/home/tomcat:/bin/bash
If $1 is the value of the variable name, the entire line is output:
[root@Srv02 ~] # more / etc/passwd | awk-F: 'BEGIN {name= "oracle"} {if ($1~name) print $0}' oracle:x:500:500::/home/oracle:/bin/bash
Introduction to awk internal variables:
NF: indicates how many columns there are.
$NF: represents the last column.
NR: represents the line number.
ORS: output record separator
OFS: output field separator
RS: record separator
[root@Srv02 ~] # tail-4 / etc/passwdoracle:x:500:500::/home/oracle:/bin/bashweblogic:x:501:503::/home/weblogic:/bin/bashtomcat:x:502:504::/home/tomcat:/bin/bashnx:x:102:158::/usr/NX/home/nx:/usr/NX/bin/nxserver [root@Srv02 ~] # tail-4 / etc/passwd | awk'{print NF} '1111 [root@Srv02 ~] # Tail-4 / etc/passwd | awk-F:'{print NF} '7777 [root@Srv02 ~] # tail-4 / etc/passwd | awk-F:' {print $NF}'/ bin/bash/bin/bash/bin/bash/usr/NX/bin/nxserver
Print the port number using awk:
[root@Srv02 ~] # netstat-ntl | awk'{if ($4 ~ "[0-9] $") print $4}'| awk-F:'{print $NF} '80018005800933801.
Make the printout display the line number:
[root@Srv02 ~] # awk-F:'{print NR,$1}'/ etc/passwd1 root2 bin3 daemon4 adm5 lp6 sync
Displays the line number of the line $1 for oracle:
[root@Srv02 ~] # more / etc/passwd | awk-F:'{if ($1 ~ "oracle") print NR}'39
Output with # as the field delimiter:
[root@Srv02 ~] # tail-4 / etc/passwd | awk-F: 'BEGIN {OFS= "#"} {print $1