博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux 三剑客 grep、sed 和 awk
阅读量:4228 次
发布时间:2019-05-26

本文共 14467 字,大约阅读时间需要 48 分钟。

grep 在使用其他语言的时候接触稍微多一些,所以就先从它开始吧!

grep

grep 指令用于查找内容包含指定的范本样式的文件,如果发现某文件的内容符合所指定的范本样式,预设 grep 指令会把含有范本样式的那一列显示出来。若不指定任何文件名称,或是所给予的文件名为 -,则 grep 指令会从标准输入设备读取数据。

参数

  • -a 或 --text : 不要忽略二进制的数据。
  • -A <显示行数> 或 --after-context=<显示行数> : 除了显示符合范本样式的那一列之外,并显示该行之后的内容。
  • -b 或 --byte-offset : 在显示符合样式的那一行之前,标示出该行第一个字符的编号。
  • -B <显示行数> 或 --before-context=<显示行数> : 除了显示符合样式的那一行之外,并显示该行之前的内容。
  • -c 或 --count : 计算符合样式的列数。
  • -C <显示行数> 或 --context=<显示行数>或-<显示行数> : 除了显示符合样式的那一行之外,并显示该行之前后的内容。
  • -d <动作> 或 --directories=<动作> : 当指定要查找的是目录而非文件时,必须使用这项参数,否则grep指令将回报信息并停止动作。
  • -e <范本样式> 或 --regexp=<范本样式> : 指定字符串做为查找文件内容的样式。
  • -E 或 --extended-regexp : 将样式为延伸的正则表达式来使用。
  • -f <规则文件> 或 --file=<规则文件> : 指定规则文件,其内容含有一个或多个规则样式,让grep查找符合规则条件的文件内容,格式为每行一个规则样式。
  • -F 或 --fixed-regexp : 将样式视为固定字符串的列表。
  • -G 或 --basic-regexp : 将样式视为普通的表示法来使用。
  • -h 或 --no-filename : 在显示符合样式的那一行之前,不标示该行所属的文件名称。
  • -H 或 --with-filename : 在显示符合样式的那一行之前,表示该行所属的文件名称。
  • -i 或 --ignore-case : 忽略字符大小写的差别。
  • -l 或 --file-with-matches : 列出文件内容符合指定的样式的文件名称。
  • -L 或 --files-without-match : 列出文件内容不符合指定的样式的文件名称。
  • -n 或 --line-number : 在显示符合样式的那一行之前,标示出该行的列数编号。
  • -o 或 --only-matching : 只显示匹配PATTERN 部分。
  • -q 或 --quiet或--silent : 不显示任何信息。
  • -r 或 --recursive : 此参数的效果和指定"-d recurse"参数相同。
  • -s 或 --no-messages : 不显示错误信息。
  • -v 或 --invert-match : 显示不包含匹配文本的所有行。
  • -V 或 --version : 显示版本信息。
  • -w 或 --word-regexp : 只显示全字符合的列。
  • -x --line-regexp : 只显示全列符合的列。
  • -y : 此参数的效果和指定"-i"参数相同。

grep df file*

在当前目录中,查找前缀有 file 字样的文件中包含 df 字符串的文件,并打印出该字符串的行。

[root@master shell_learning]# grep df file*file1:dffile1:dfdfile2:dffile2:dfd

grep -r world ./ 

从当前目录开始,以递归的方式查找符合条件的文件,并打印出对应字符串的行。 

[root@master shell_learning]# grep -r world ././logs/test.txt:hello world./file1:world./test.txt:hello world

grep -v world file1 

 反向查找。前面各个例子是查找并打印出符合条件的行,通过 "-v" 参数可以打印出不符合条件行的内容。

[root@master shell_learning]# grep world file1 world[root@master shell_learning]# grep -v world file1dfdfd

grep -n echo test.sh 

-n 参数显示匹配行数

[root@master shell_learning]# grep -n echo test.sh   5:echo $greeting6:echo $greeting27:echo $greeting311:echo $greeting412:echo $greeting5

grep -E "e.{2}o" test.sh

-E --extended-regexp : 将样式为延伸的正则表达式来使用。从文件内容查找与正则表达式匹配的行。

[root@master shell_learning]# grep -E "e.{2}o" test.shgreeting="hello, "$your_name" !"greeting2="hello, $your_name !"greeting3="hello, ${your_name} !"echo $greetingecho $greeting2echo $greeting3greeting4='hello, '$your_name' !'greeting5='hello, ${your_name} !'echo $greeting4echo $greeting5

grep -i "looking" test.sh 

查找时不区分大小写

[root@master shell_learning]# grep "looking" test.sh [root@master shell_learning]# grep -i "looking" test.shyour_name="Looking"

find . -name "file*" | xargs grep "df" 

从当前目录开始查找所有前缀为 file 的文本文件,并找出包含 "df" 的行

[root@master shell_learning]# find . -name "file*" | xargs grep "df"./file2:df./file2:dfd./file1:df./file1:dfd

sed

sed 主要用来自动编辑一个或多个文件、简化对文件的反复操作、编写转换程序等。

-i 参数表示对操作的原文件进行修改(所以谨慎使用 -i 参数)。

参数说明

  • -e <script>或--expression=<script> 以选项中指定的script来处理输入的文本文件。
  • -f <script文件>或--file=<script文件> 以选项中指定的script文件来处理输入的文本文件。
  • -h 或--help 显示帮助。
  • -i 修改文件内容。
  • -n 或--quiet或--silent 仅显示script处理后的结果。
  • -V 或--version 显示版本信息。

动作说明

  • a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
  • c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
  • d :删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
  • i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
  • p :打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~
  • s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!

以行为单位的新增/删除

sed '2a Looking' test.txt 

[root@master shell_learning]# cat test.txthello worldNice to meet you[root@master shell_learning]# sed '2a Looking' test.txthello worldNice to meet youLooking# 添加多行[root@master shell_learning]# sed '2a newLine\nnewline' test.txtworld worldNice to meet younewLinenewline

sed '2,$d' test.sh

$ 在这儿表示最后的意思,可以是具体的行的数字。

[root@master shell_learning]# cat test.shyour_name="Looking"greeting="hello, "$your_name" !"greeting2="hello, $your_name !"greeting3="hello, ${your_name} !"echo $greetingecho $greeting2echo $greeting3 greeting4='hello, '$your_name' !'greeting5='hello, ${your_name} !'echo $greeting4echo $greeting5[root@master shell_learning]# sed '2,$d' test.shyour_name="Looking"

以行为单位的替换与显示 

sed '2c No 2 number' test.txt 

[root@master shell_learning]# cat test.txthello worldNice to meet youNice to meet you[root@master shell_learning]# sed '2c No 2 number' test.txt hello worldNo 2 numberNice to meet you

sed '2,3c No 2-3 number' test.txt 

[root@master shell_learning]# cat test.txt                  hello worldNice to meet youNice to meet you[root@master shell_learning]# sed '2,3c No 2-3 number' test.txthello worldNo 2-3 number

 sed -n '2,3p' test.sh

[root@master shell_learning]# cat test.shyour_name="Looking"greeting="hello, "$your_name" !"greeting2="hello, $your_name !"greeting3="hello, ${your_name} !"echo $greetingecho $greeting2echo $greeting3 greeting4='hello, '$your_name' !'greeting5='hello, ${your_name} !'echo $greeting4echo $greeting5[root@master shell_learning]# sed -n '2,3p' test.shgreeting="hello, "$your_name" !"greeting2="hello, $your_name !"

数据的搜索

数据的搜索并显示

sed -n '/hello/p' test.sh

[root@master shell_learning]# cat test.shyour_name="Looking"greeting="hello, "$your_name" !"greeting2="hello, $your_name !"greeting3="hello, ${your_name} !"echo $greetingecho $greeting2echo $greeting3 greeting4='hello, '$your_name' !'greeting5='hello, ${your_name} !'echo $greeting4echo $greeting5[root@master shell_learning]# sed -n '/hello/p' test.shgreeting="hello, "$your_name" !"greeting2="hello, $your_name !"greeting3="hello, ${your_name} !"greeting4='hello, '$your_name' !'greeting5='hello, ${your_name} !'

数据的搜索并删除

sed '/hello/d' test.sh

[root@master shell_learning]# cat test.shyour_name="Looking"greeting="hello, "$your_name" !"greeting2="hello, $your_name !"greeting3="hello, ${your_name} !"echo $greetingecho $greeting2echo $greeting3 greeting4='hello, '$your_name' !'greeting5='hello, ${your_name} !'echo $greeting4echo $greeting5[root@master shell_learning]# sed '/hello/d' test.shyour_name="Looking"echo $greetingecho $greeting2echo $greeting3 echo $greeting4echo $greeting5

数据的搜索并替换

sed 's/world/hello/g' test.txt

[root@master shell_learning]# cat test.txthello worldNice to meet youNice to meet you[root@master shell_learning]# sed 's/world/hello/g' test.txthello helloNice to meet youNice to meet you

数据的搜索并修改(直接修改原文件)

sed -i 's/world/hello/g' test.txt 

[root@master shell_learning]# cat test.txt hello worldNice to meet youNice to meet you[root@master shell_learning]# sed -i 's/hello/world/g' test.txt[root@master shell_learning]# cat test.txt                     world worldNice to meet youNice to meet you

awk

awk 是一种处理文本文件的语言,是一个强大的文本分析工具。

参数:

  • -F fs or --field-separator fs
    指定输入文件折分隔符,fs是一个字符串或者是一个正则表达式,如-F:。
  • -v var=value or --asign var=value
    赋值一个用户定义变量。
  • -f scripfile or --file scriptfile
    从脚本文件中读取awk命令。

hello world

awk 'BEGIN {print "hello world!"}'

[root@master shell_learning]# awk 'BEGIN {print "hello world!"}'hello world!

基本用法

awk '{print $1, $4}' log.txt

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '{print $1, $4}' log.txt2 a3 likeThis's 10 orange,apple,mongo

awk '{printf "%-8s %-10s\n", $1, $4}' log.txt 

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '{printf "%-8s %-10s\n", $1, $4}' log.txt2        a         3        like      This's             10       orange,apple,mongo

awk -F, '{print $1, $2}' 

指定分割字符

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk -F\' '{print $1, $2}' log.txt2 this is a test 3 Are you like awk This s a test10 There are orange,apple,mongo [root@master shell_learning]# awk -F, '{print $1, $2}' log.txt2 this is a test 3 Are you like awk This's a test 10 There are orange apple[root@master shell_learning]# awk 'BEGIN{FS=","} {print $1, $2}' log.txt2 this is a test 3 Are you like awk This's a test 10 There are orange apple

awk -F '[ ,]' '{print $1, $2, $5}' log.txt

指定多个分割符

[root@master shell_learning]# awk -F '[ ,]' '{print $1, $2, $5}' log.txt2 this test3 Are awkThis's a 10 There apple

awk -v a=2 '{print $1, $1+a}' log.txt

设置变量

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk -v a=2 '{print $1, $1+a}' log.txt2 43 5This's 210 12

awk '$1>2' log.txt

过滤第一列大于 2 的行

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '$1>2' log.txt3 Are you like awkThis's a test10 There are orange,apple,mongo

awk '$1==2' log.txt

过滤第一列等于 2 的行

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '$1==2' log.txt2 this is a test

awk '$1>2 && $2=="Are"' log.txt 

过滤第一列大于 2 同时第二列为 ‘Are' 的行

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '$1>2 && $2=="Are"' log.txt3 Are you like awk[root@master shell_learning]# awk '$1>2 && $2=="Are" {print $1, $2, $3}' log.txt3 Are you

内建变量

变量 描述
$n 当前记录的第n个字段,字段间由FS分隔
$0 完整的输入记录
ARGC 命令行参数的数目
ARGIND 命令行中当前文件的位置(从0开始算)
ARGV 包含命令行参数的数组
CONVFMT 数字转换格式(默认值为%.6g)ENVIRON环境变量关联数组
ERRNO 最后一个系统错误的描述
FIELDWIDTHS 字段宽度列表(用空格键分隔)
FILENAME 当前文件名
FNR 各文件分别计数的行号
FS 字段分隔符(默认是任何空格)
IGNORECASE 如果为真,则进行忽略大小写的匹配
NF 一条记录的字段的数目
NR 已经读出的记录数,就是行号,从1开始
OFMT 数字的输出格式(默认值是%.6g)
OFS 输出记录分隔符(输出换行符),输出时用指定的符号代替换行符
ORS 输出记录分隔符(默认值是一个换行符)
RLENGTH 由match函数所匹配的字符串的长度
RS 记录分隔符(默认是一个换行符)
RSTART 由match函数所匹配的字符串的第一个位置
SUBSEP 数组下标分隔符(默认值是/034)

内建变量初识 

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk 'BEGIN{printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n","FILENAME","ARGC","FNR","FS","NF","NR","OFS","ORS","RS";printf "------------------------------------------------\n"} {printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s",FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS}' log.txtFILENAME ARGC  FNR   FS   NF   NR  OFS  ORS   RS------------------------------------------------log.txt    2    1         5    1             log.txt    2    2         5    2         log.txt    2    3         3    3         log.txt    2    4         4    4             [root@master shell_learning]# awk -F\' 'BEGIN{printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n","FILENAME","ARGC","FNR","FS","NF","NR","OFS","ORS","RS";printf "------------------------------------------------\n"} {printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s",FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS}' log.txtFILENAME ARGC  FNR   FS   NF   NR  OFS  ORS   RS------------------------------------------------log.txt    2    1    '    1    1             log.txt    2    2    '    1    2             log.txt    2    3    '    2    3             log.txt    2    4    '    1    4

awk '{print $1,$2,$3}' OFS=" $ " log.txt

指定输出分隔符

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '{print NR,FNR,$1,$2,$3}' log.txt1 1 2 this is2 2 3 Are you3 3 This's a test4 4 10 There are[root@master shell_learning]# awk '{print $1,$2,$3}' OFS=" $ " log.txt2 $ this $ is3 $ Are $ youThis's $ a $ test10 $ There $ are

正则字符串匹配

awk '$2 ~ /re/' log.txt

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '$2 ~ /th/' log.txt 2 this is a test[root@master shell_learning]# awk '$2 ~ /re/' log.txt3 Are you like awk10 There are orange,apple,mongo

忽略大小写

awk 'BEGIN{IGNORECASE=1} /this/' log.txt

[root@master shell_learning]# cat log.txt2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk 'BEGIN{IGNORECASE=1} /this/' log.txt2 this is a testThis's a test

模式取反

awk '$2 !~ /th/' log.txt 

[root@master shell_learning]# cat log.txt                             2 this is a test3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk '$2 !~ /th/' log.txt 3 Are you like awkThis's a test10 There are orange,apple,mongo[root@master shell_learning]# awk 'BEGIN{IGNORECASE=1} !/th/' log.txt3 Are you like awk

awk 脚本

关于 awk 脚本,我们需要注意两个关键词 BEGIN 和 END。

  • BEGIN { 这里面放的是执行前的语句 }
  • END {这里面放的是处理完所有的行后要执行的语句 }
  • {这里面放的是处理每一行时要执行的语句}
[root@master shell_learning]# cat score.txt           Marry   2143 78 84 77Jack    2321 66 78 45Tom     2122 48 77 71Mike    2537 87 97 95Bob     2415 40 57 62[root@master shell_learning]# cat cal.awk#!/bin/awk -f#运行前BEGIN {    math = 0    english = 0    computer = 0     printf "NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL\n"    printf "---------------------------------------------\n"}#运行中{    math+=$3    english+=$4    computer+=$5    printf "%-6s %-6s %4d %8d %8d %8d\n", $1, $2, $3,$4,$5, $3+$4+$5}#运行后END {    printf "---------------------------------------------\n"    printf "  TOTAL:%10d %8d %8d \n", math, english, computer    printf "AVERAGE:%10.2f %8.2f %8.2f\n", math/NR, english/NR, computer/NR}[root@master shell_learning]# awk -f cal.awk score.txtNAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL---------------------------------------------Marry  2143     78       84       77      239Jack   2321     66       78       45      189Tom    2122     48       77       71      196Mike   2537     87       97       95      279Bob    2415     40       57       62      159---------------------------------------------  TOTAL:       319      393      350 AVERAGE:     63.80    78.60    70.00

其他实例

计算文件大小

[root@master shell_learning]# ls -l *.txt-rw-rw-r-- 1 lukaiyi lukaiyi  51 Sep 18 10:57 in.txt-rw-rw-r-- 1 lukaiyi lukaiyi  82 Sep 27 17:17 log.txt-rw-rw-r-- 1 lukaiyi lukaiyi 110 Sep 28 15:19 score.txt-rw-rw-r-- 1 lukaiyi lukaiyi  24 Sep 27 17:42 test.txt-rw-rw-r-- 1 lukaiyi lukaiyi 276 Sep 27 16:10 ttt.txt[root@master shell_learning]# ls -l *.txt | awk '{sum+=$5} END {print sum}'543

九九乘法表

[root@master shell_learning]# 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")}'1x1=11x2=2	2x2=41x3=3	2x3=6	3x3=91x4=4	2x4=8	3x4=12	4x4=161x5=5	2x5=10	3x5=15	4x5=20	5x5=251x6=6	2x6=12	3x6=18	4x6=24	5x6=30	6x6=361x7=7	2x7=14	3x7=21	4x7=28	5x7=35	6x7=42	7x7=491x8=8	2x8=16	3x8=24	4x8=32	5x8=40	6x8=48	7x8=56	8x8=641x9=9	2x9=18	3x9=27	4x9=36	5x9=45	6x9=54	7x9=63	8x9=72	9x9=81

 

转载地址:http://xjjqi.baihongyu.com/

你可能感兴趣的文章
C++ Network Programming, Volume 2: Systematic Reuse with ACE and Frameworks
查看>>
Java 6 Platform Revealed
查看>>
Beginning ASP.NET 2.0 Databases: From Novice to Professional
查看>>
Microsoft Windows 2000 Scripting Guide
查看>>
Visual Basic .NET Bible
查看>>
The Struts Framework: Practical Guide for Java Programmers
查看>>
C#.net Web Developer's Guide
查看>>
Virtualization with VMware ESX Server
查看>>
System Architecture with XML
查看>>
Microsoft SQL Server 2005 Stored Procedure Programming in T-SQL & .NET
查看>>
Sams Teach Yourself Microsoft Office Access 2003 in 24 Hours
查看>>
Leveraging Web Services: Planning, Building, and Integration for Maximum Impact
查看>>
Implementing Backup and Recovery: The Readiness Guide for the Enterprise
查看>>
Wireless Communications over MIMO Channels: Applications to CDMA and Multiple Antenna Systems
查看>>
UMTS Performance Measurement: A Practical Guide to KPIs for the UTRAN Environment
查看>>
Grid Networks: Enabling Grids with Advanced Communication Technology
查看>>
Communication Systems for the Mobile Information Society
查看>>
Beginning Ubuntu Linux: From Novice to Professional
查看>>
IPsec Virtual Private Network Fundamentals
查看>>
Algorithms and Networking for Computer Games
查看>>