Introduction to shell programming four swordsman find sed grep awk (micro-channel public number excerpt)

A, Shell programming four swordsman's Find

With the above basic grammar learning, readers have to program one step closer to understanding Shell, Shell programming is no longer a simple command accumulation, but evolved into a variety of special statements, various syntax, programming tools, various commands collection.

In the Shell programming tool, a four swordsman tools more widely, Shell Programming four swordsman include: find, sed, grep, awk, master swordsman will greatly enhance the four Shell programming capabilities.

Find practical tool, the Find tool four swordsman mainly used to find the operating system files, directories, and its syntax in the format:

find   path   -option   [   -print ]   [ -exec   -ok   command ]   { }  \;

Detailed option common parameters which are as follows:

-name filename # find the file called filename;

-type b / d / c / p / l / f # search block device, directory, character devices, pipes, symbolic links, normal file;

-size n [c] # search block length n [n or byte] of the document;

-perm # Press Execute permission to search;

-user username # by file owner to find;

-group groupname # in groups to find;

-mtime -n + n # by file to change the time to find the file, -n refers to within n days, + n n refers days ago;

-atime -n + n # by file access times to find the file;

-ctime -n + n # by file creation time to find the file;

-mmin -n + n # by file to change the time to find the file, -n means that within minutes n, + n n refers minutes ago;

-amin -n + n # by file access times to find the file;

-cmin -n + n # by file creation time to find the file;

-nogroup # No results file is a valid group;

-nouser # check without a valid owner of the file;

! -Newer f1 f2 # to find the file, -n refers to within n days, + n n refers days ago;

-depth # make finding before entering subdirectory ahead now search the catalog;

-fstype # check for changes longer than f1 f2 than the new but the old files;

-mount # do not cross file system mount point when the investigation file;

-follow # If you encounter a symbolic link file, it referred to the trace file link;

-cpio # check file located in a certain type of file system;

-prune # ignore a directory;

-maxdepth # find the directory levels deep.

(1) Find tool parameters -name seen cases:

find / data / -name "* .txt" # Find / data / directory to .txt files ending;

find / data / -name "[AZ] *" # Find / data / directory with a capital letter at the beginning of the file;

find / data / -name "test *" # Find / data / directory to test files that begin with;

(2) Find tool -type parameters Case column:

find / data / -type d # find files in the / data / directory folder;

! Find / data / -type d # find files in non / data / directory folder;

find / data / -type l # Find links to files in the / data / directory.

find  /data/ -type d|xargs chmod 755 -R  #查目录类型并将权限设置为755;

find  /data/ -type f|xargs chmod 644 -R  #查文件类型并将权限设置为644;

(3) Find工具-size参数案列:

find   /data/    -size   +1M              #查文件大小大于1Mb的文件;

find   /data/    -size   10M             #查文件大小为10M的文件;

find   /data/    -size   -1M             #查文件大小小于1Mb的文件;

(4) Find工具-perm参数案列:

find   /data/    -perm   755     #查找/data/目录权限为755的文件或者目录;

find   /data/    -perm   -007     #与-perm 777相同,表示所有权限;

find   /data/    -perm   +644         #文件权限符号644以上;

(5) Find工具-mtime参数案列:

atime,access time   文件被读取或者执行的时间;

ctime,change time   文件状态改变时间;

mtime,modify time   文件内容被修改的时间;

find /data/ -mtime +30  -name  "*.log"   #查找30天以前的log文件;

find /data/ -mtime -30  -name  "*.txt"   #查找30天以内的log文件;

find /data/ -mtime 30  -name   "*.txt" #查找第30天的log文件;

find /data/ -mmin  +30 -name   "*.log"   #查找30分钟以前修改的log文件;

find /data/ -amin  -30  -name   "*.txt"   #查找30分钟以内被访问的log文件;

find /data/ -cmin  30  -name   "*.txt" #查找第30分钟改变的log文件。

(6) Find工具参数综合案列:

#查找/data目录以.log结尾,文件大于10k的文件,同时cp到/tmp目录;

find /data/ -name "*.log"  –type f  -size +10k -exec cp {} /tmp/ \;

#查找/data目录以.txt结尾,文件大于10k的文件,权限为644并删除该文件;

find /data/ -name "*.log"  –type f  -size +10k  -m perm 644 -exec rm –rf {} \;

#查找/data目录以.log结尾,30天以前的文件,大小大于10M并移动到/tmp目录;

find /data/ -name "*.log"  –type f  -mtime +30 –size +10M -exec mv {} /tmp/ \;

 

二,Shell编程四剑客之SED

SED是一个非交互式文本编辑器,它可对文本文件和标准输入进行编辑,标准输入可以来自键盘输入、文本重定向、字符串、变量,甚至来自于管道的文本,与VIM编辑器类似,它一次处理一行内容,Sed可以编辑一个或多个文件,简化对文件的反复操作、编写转换程序等。

在处理文本时把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),紧接着用SED命令处理缓冲区中的内容,处理完成后把缓冲区的内容输出至屏幕或者写入文件。

逐行处理直到文件末尾,然而如果打印在屏幕上,实质文件内容并没有改变,除非你使用重定向存储输出或者写入文件。其语法参数格式为:

sed    [-Options]     [‘Commands’]    filename;

sed工具默认处理文本,文本内容输出屏幕已经修改,但是文件内容其实没有修改,需要加-i参数即对文件彻底修改;

x                     #x为指定行号;

x,y                       #指定从x到y的行号范围;

/pattern/                 #查询包含模式的行;

/pattern/pattern/             #查询包含两个模式的行;

/pattern/,x               #从与pattern的匹配行到x号行之间的行;

x,/pattern/               #从x号行到与pattern的匹配行之间的行;

x,y!                      #查询不包括x和y行号的行;

r                   #从另一个文件中读文件;

w                   #将文本写入到一个文件;

y                   #变换字符;

q                 #第一个模式匹配完成后退出;

l                   #显示与八进制ASCII码等价的控制字符;

{}                     #在定位行执行的命令组;

p                   #打印匹配行;

=                   #打印文件行号;

a\                     #在定位行号之后追加文本信息;

i\                     #在定位行号之前插入文本信息;

d                   #删除定位行;

c\                     #用新文本替换定位文本;

s                   #使用替换模式替换相应模式;

n                   #读取下一个输入行,用下一个命令处理新的行;

N                           #将当前读入行的下一行读取到当前的模式空间。

h                   #将模式缓冲区的文本复制到保持缓冲区;

H                   #将模式缓冲区的文本追加到保持缓冲区;

x                   #互换模式缓冲区和保持缓冲区的内容;

g                   #将保持缓冲区的内容复制到模式缓冲区;

G                   #将保持缓冲区的内容追加到模式缓冲区。

常用SED工具企业演练案列:

(1) 替换jfedu.txt文本中old为new:

sed    's/old/new/g'       jfedu.txt

(2) 打印jfedu.txt文本第一行至第三行:

sed    -n  '1,3p'           jfedu.txt

(3) 打印jfedu.txt文本中第一行与最后一行:

sed    -n '1p;$p'           jfedu.txt

(4) 删除jfedu.txt第一行至第三行、删除匹配行至最后一行:

sed       '1,3d'             jfedu.txt

sed       '/jfedu/,$d'         jfedu.txt

(5) 删除jfedu.txt最后6行及删除最后一行:

for   i  in `seq 1 6`;do  sed  -i   '$d'  jfedu.txt ;done

sed       '$d'               jfedu.txt

(6) 删除jfedu.txt最后一行:

sed       '$d'             jfedu.txt

(7) 在jfedu.txt查找jfedu所在行,并在其下一行添加word字符,a表示在其下一行添加字符串:

sed    '/jfedu/aword'      jfedu.txt

(8) 在jfedu.txt查找jfedu所在行,并在其上一行添加word字符,i表示在其上一行添加字符串:

sed    '/jfedu/iword'       jfedu.txt

(9) 在jfedu.txt查找以test结尾的行尾添加字符串word,$表示结尾标识,&在Sed中表示添加:

sed   's/test$/&word/g'     jfedu.txt

(10) 在jfedu.txt查找www的行,在其行首添加字符串word,^表示起始标识,&在Sed中表示添加:

sed   '/www/s/^/&word/'    jfedu.txt

(11) 多个sed命令组合,使用-e参数:

sed  -e  '/www.jd.com/s/^/&1./'  -e  's/www.jd.com$/&./g'  jfedu.txt

(12) 多个sed命令组合,使用分号“;”分割:

sed  -e  '/www.jd.com/s/^/&1./;s/www.jd.com$/&./g'  jfedu.txt

(13) Sed读取系统变量,变量替换:

WEBSITE=WWW.JFEDU.NET

Sed  “s/www.jd.com/$WEBSITE/g” jfedu.txt

(14) 修改Selinux策略enforcing为disabled,查找/SELINUX/行,然后将其行enforcing值改成disabled、!s表示不包括SELINUX行:

sed  -i   '/SELINUX/s/enforcing/disabled/g' /etc/selinux/config

sed  -i   '/SELINUX/!s/enforcing/disabled/g' /etc/selinux/config

通常而言,SED将待处理的行读入模式空间,脚本中的命令逐行进行处理,直到脚本执行完毕,然后该行被输出,模式空间请空;然后重复刚才的动作,文件中的新的一行被读入,直到文件处理完备。

如果用户希望在某个条件下脚本中的某个命令被执行,或者希望模式空间得到保留以便下一次的处理,都有可能使得sed在处理文件的时候不按照正常的流程来进行。这时可以使用SED高级语法来满足用户需求。总的来说,SED高级命令可以分为三种功能:

q N、D、P:处理多行模式空间的问题;

q H、h、G、g、x:将模式空间的内容放入存储空间以便接下来的编辑;

q :、b、t:在脚本中实现分支与条件结构。

(1) 在jfedu.txt每行后加入空行,也即每行占永两行空间,每一行后边插入一行空行、两行空行及前三行每行后插入空行:

sed     '/^$/d;G'            jfedu.txt

sed     '/^$/d;G;G'      jfedu.txt

sed     '/^$/d;1,3G;'     jfedu.txt

(2) 将jfedu.txt偶数行删除及隔两行删除一行:

sed    'n;d'              jfedu.txt

sed    'n;n;d'           jfedu.txt

(3) 在jfedu.txt匹配行前一行、后一行插入空行以及同时在匹配前后插入空行:

sed  '/jfedu/{x;p;x;}'      jfedu.txt

sed  '/jfedu/G'                jfedu.txt

sed  '/jfedu/{x;p;x;G;}'   jfedu.txt

(4) 在jfedu.txt每行后加入空行,也即每行占永两行空间,每一行后边插入空行:

sed '/^$/d;G' jfedu.txt

(5) 在jfedu.txt每行后加入空行,也即每行占永两行空间,每一行后边插入空行:

sed '/^$/d;G' jfedu.txt

(6) 在jfedu.txt每行前加入顺序数字序号、加上制表符\t及.符号:

sed = jfedu.txt| sed 'N;s/\n/ /'

sed = jfedu.txt| sed 'N;s/\n/\t/'

sed = jfedu.txt| sed 'N;s/\n/\./'

(7) 删除jfedu.txt行前和行尾的任意空格:

sed 's/^[ \t]*//;s/[ \t]*$//' jfedu.txt

(8) 打印jfedu.txt关键词old与new之间的内容:

sed -n '/old/,/new/'p     jfedu.txt

(9) 打印及删除jfedu.txt最后两行:

sed   '$!N;$!D'             jfedu.txt

sed   'N;$!P;$!D;$d'      jfedu.txt

(10) 合并上下两行,也即两行合并:

sed    '$!N;s/\n/ /'          jfedu.txt

sed    'N;s/\n/ /'            jfedu.txt

 三,Shell编程四剑客之AWK

AWK是一个优良的文本处理工具,LinuxUnix环境中现有的功能最强大的数据处理引擎之一,以Aho、Weinberger、Kernighan三位发明者名字首字母命名为AWK,AWK是一个行级文本高效处理工具,AWK经过改进生成的新的版本有Nawk、Gawk,一般Linux默认为Gawk,Gawk是 AWK的GNU开源免费版本。

AWK基本原理是逐行处理文件中的数据,查找与命令行中所给定内容相匹配的模式,如果发现匹配内容,则进行下一个编程步骤,如果找不到匹配内容,则  继续处理下一行。其语法参数格式为,AWK常用参数、变量、函数详解如下:

awk    'pattern   +   {action}'     file

(1) AWK基本语法参数详解:

q 单引号' '是为了和shell命令区分开;

q 大括号{ }表示一个命令分组;

q pattern是一个过滤器,表示匹配pattern条件的行才进行Action处理;

q action是处理动作,常见动作为Print;

q 使用#作为注释,pattern和action可以只有其一,但不能两者都没有。

(2) AWK内置变量详解:

q FS 分隔符,默认是空格;

q OFS 输出分隔符;

q NR 当前行数,从1开始;

q NF 当前记录字段个数;

q $0 当前记录;

q $1~$n 当前记录第n个字段(列)。

(3) AWK内置函数详解:

q gsub(r,s):在$0中用s代替r;

q index(s,t):返回s中t的第一个位置;

q length(s):s的长度;

q match(s,r):s是否匹配r;

q split(s,a,fs):在fs上将s分成序列a;

q substr(s,p):返回s从p开始的子串。

(4) AWK常用操作符,运算符及判断符:

q ++ --                     增加与减少( 前置或后置);

q ^ **                      指数( 右结合性);

q ! + -                     非、一元(unary) 加号、一元减号;

q + - * / %                    加、减、乘、除、余数;

q < <= == != > >=      数字比较;

q &&                      逻辑and;

q ||                      逻辑or;

q = += -= *= /= %= ^= **=   赋值。

(5) AWK与流程控制语句:

q if(condition) { } else { };

q while { };

q do{ }while(condition);

q for(init;condition;step){ };

q break/continue。

常用AWK工具企业演练案列:

(1) AWK打印硬盘设备名称,默认以空格为分割:

df    -h|awk  '{print  $1}'

(2) AWK以空格、冒号、\t、分号为分割:

awk  -F '[ :\t;]'  '{print  $1}'            jfedu.txt

(3) AWK以冒号分割,打印第一列,同时将内容追加到/tmp/awk.log下:

awk  -F:  '{print $1 >>"/tmp/awk.log"}'  jfedu.txt

(4) 打印jfedu.txt文件中的第3行至第5行,NR表示打印行,$0表示文本所有域:

awk 'NR==3,NR==5  {print}'             jfedu.txt

awk 'NR==3,NR==5  {print $0}'          jfedu.txt

(5) 打印jfedu.txt文件中的第3行至第5行的第一列与最后一列:

awk 'NR==3,NR==5 {print $1,$NF}'       jfedu.txt

(6) 打印jfedu.txt文件中,长度大于80的行号:

awk   'length($0)>80 {print NR}'        jfedu.txt

(7) AWK引用Shell变量,使用-v或者双引号+单引号即可:

awk -v STR=hello  '{print STR,$NF}'      jfedu.txt

STR="hello";echo| awk  '{print "'${STR}'";}'

(8) AWK以冒号切割,打印第一列同时只显示前5行:

cat  /etc/passwd|head -5|awk  -F:   '{print $1}'

awk  -F:  'NR>=1&&NR<=5 {print $1}'  /etc/passwd

(9) Awk指定文件jfedu.txt第一列的总和:

cat jfedu.txt |awk '{sum+=$1}END{print sum}'

(10) AWK NR行号除以2余数为0则跳过该行,继续执行下一行,打印在屏幕:

awk  -F:  'NR%2==0 {next} {print NR,$1}'  /etc/passwd

(11) AWK添加自定义字符:

ifconfig  eth0|grep "Bcast"|awk '{print "ip_"$2}'

(12) AWK格式化输出passwd内容,printf打印字符串,%格式化输出分隔符,s表示字符串类型,-12表示12个字符,-6表示6个字符:

awk -F:  '{printf "%-12s %-6s %-8s\n",$1,$2,$NF}'  /etc/passwd

(13) AWK OFS输出格式化\t:

netstat -an|awk '$6 ~ /LISTEN/&&NR>=1&&NR<=10 {print NR,$4,$5,$6}' OFS="\t"  

(14) AWK与if组合实战,判断数字比较:

echo 3 2 1 | awk '{ if(($1>$2)||($1>$3)) { print $2} else {print $1} }'

(15) AWK与数组组合实战,统计passwd文件用户数:

awk -F ':' 'BEGIN {count=0;} {name[count] = $1;count++;};END{for (i = 0;i < NR;i++) print i, name[i]}'  /etc/passwd

(16) awk分析Nginx访问日志的状态码404、502等错误信息页面,统计次数大于20的IP地址。

awk '{if ($9~/502|499|500|503|404/) print $1,$9}' access.log|sort|uniq –c|sort –nr | awk '{if($1>20) print $2}'

(17) 用/etc/shadow文件中的密文部分替换/etc/passwd中的"x"位置,生成新的/tmp/passwd文件。

awk 'BEGIN{OFS=FS=":"} NR==FNR{a[$1]=$2}NR>FNR{$2=a[$1];print >>"/tmp/passwd"}' /etc/shadow /etc/passwd

(18) Awk统计服务器状态连接数:

netstat -an | awk '/tcp/ {s[$NF]++} END {for(a in s) {print a,s[a]}}'

netstat -an | awk '/tcp/ {print $NF}' | sort | uniq -c

 

四,Shell编程四剑客之GREP

全面搜索正则表达式(Global search regular expression(RE) ,GREP)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

Unix/Linux的grep家族包括grep、egrep和fgrep,其中egrep和fgrep的命令跟grep有细微的区别,egrep是grep的扩展,支持更多的re元字符, fgrep是fixed grep或fast grep简写,它们把所有的字母都看作单词,正则表达式中的元字符表示其自身的字面意义,不再有其他特殊的含义,一般使用比较少。

目前Linux操作系统默认使用GNU版本的grep。它功能更强,可以通过-G、-E、-F命令行选项来使用egrep和fgrep的功能。其语法格式及常用参数详解如下:

grep     -[acinv]    'word'     Filename

Grep常用参数详解如下:

-a       以文本文件方式搜索;

-c       计算找到的符合行的次数;

-i       忽略大小写;

-n       顺便输出行号;

-v       反向选择,即显示不包含匹配文本的所有行;

-h       查询多文件时不显示文件名;

-l       查询多文件时只输出包含匹配字符的文件名;

-s       不显示不存在或无匹配文本的错误信息;

-E       允许使用egrep扩展模式匹配。

学习Grep时,需要了解通配符、正则表达式两个概念,很多读者容易把彼此搞混淆,通配符主要用在Linux的Shell命令中,常用于文件或者文件名称的操作,而正则表达式用于文本内容中的字符串搜索和替换,常用在AWK、GREP、SED、VIM工具中对文本的操作。

通配符类型详解:

*      0个或者多个字符、数字;

?      匹配任意一个字符;

#      表示注解;

|      管道符号;

;     多个命令连续执行;

&      后台运行指令;

!      逻辑运算非;

[ ]      内容范围,匹配括号中内容;

{ }      命令块,多个命令匹配。

正则表达式详解:

*      前一个字符匹配0次或多次;

.      匹配除了换行符以外任意一个字符;

.*      代表任意字符;

^      匹配行首,即以某个字符开头;

$      匹配行尾,即以某个字符结尾;

\(..\)      标记匹配字符;

[]      匹配中括号里的任意指定字符,但只匹配一个字符;

[^]      匹配除中括号以外的任意一个字符;

\      转义符,取消特殊含义;

\<       锚定单词的开始;

\>       锚定单词的结束;

{n}      匹配字符出现n次;

{n,}     匹配字符出现大于等于n次;

{n,m}     匹配字符至少出现n次,最多出现m次;

\w       匹配文字和数字字符;

\W       \w的反置形式,匹配一个或多个非单词字符;

\b       单词锁定符;

\s      匹配任何空白字符;

\d      匹配一个数字字符,等价于[0-9]。

常用GREP工具企业演练案列:

grep  -c "test"       jfedu.txt  统计test字符总行数;

grep  -i "TEST"       jfedu.txt  不区分大小写查找TEST所有的行;

grep  -n "test"       jfedu.txt  打印test的行及行号;

grep  -v "test"       jfedu.txt  不打印test的行;

grep  "test[53]"       jfedu.txt  以字符test开头,接5或者3的行;

grep  "^[^test]"       jfedu.txt  显示输出行首不是test的行;

grep  "[Mm]ay"     jfedu.txt  匹配M或m开头的行;

grep  "K…D"    jfedu.txt  匹配K,三个任意字符,紧接D的行;

grep  "[A-Z][9]D"    jfedu.txt  匹配大写字母,紧跟9D的字符行;

grep  "T\{2,\}"       jfedu.txt  打印字符T字符连续出现2次以上的行;

grep  "T\{4,6\}"       jfedu.txt  打印字符T字符连续出现4次及6次的行;

grep  -n "^$"     jfedu.txt  打印空行的所在的行号;

grep  -vE "#|^$"       jfedu.txt    不匹配文件中的#和空行;

grep   --color -ra -E "db|config|sql"  *  匹配包含db或者config或者sql的文件;

grep   --color -E "\<([0-9]{1,3}\.){3}([0-9]{1,3})\>"    jfedu.txt 匹配IPV4地址。

Guess you like

Origin www.cnblogs.com/Lonelychampion/p/11427598.html