主頁 >  其他 > Linux 正則與三劍客grep、sed、awk

Linux 正則與三劍客grep、sed、awk

2021-02-13 10:35:04 其他

0x00 前言

終于!終于!終于!時隔多年后,終于要認真學一次了!

先放正則相關的圖,留存查詢
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

另外一定要注意:語系編碼對正則同樣是有影響的!

三劍客的功能非常強大,但我們只需要掌握他們分別擅長的領域即可

  • grep擅長查找功能
  • sed擅長取行和替換
  • awk擅長取列

0x01 grep

grep是日常用的最多的也是最熟悉的了

[root@localhost ~]grep --help
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.c

Regexp selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
  -F, --fixed-strings       PATTERN is a set of newline-separated fixed strings
  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  -e, --regexp=PATTERN      use PATTERN for matching
  -f, --file=FILE           obtain PATTERN from FILE
  -i, --ignore-case         ignore case distinctions
  -w, --word-regexp         force PATTERN to match only whole words
  -x, --line-regexp         force PATTERN to match only whole lines
  -z, --null-data           a data line ends in 0 byte, not newline

Miscellaneous:
  -s, --no-messages         suppress error messages
  -v, --invert-match        select non-matching lines
  -V, --version             display version information and exit
      --help                display this help text and exit

Output control:
  -m, --max-count=NUM       stop after NUM matches
  -b, --byte-offset         print the byte offset with output lines
  -n, --line-number         print line number with output lines
      --line-buffered       flush output on every line
  -H, --with-filename       print the file name for each match
  -h, --no-filename         suppress the file name prefix on output
      --label=LABEL         use LABEL as the standard input file name prefix
  -o, --only-matching       show only the part of a line matching PATTERN
  -q, --quiet, --silent     suppress all normal output
      --binary-files=TYPE   assume that binary files are TYPE;
                            TYPE is 'binary', 'text', or 'without-match'
  -a, --text                equivalent to --binary-files=text
  -I                        equivalent to --binary-files=without-match
  -d, --directories=ACTION  how to handle directories;
                            ACTION is 'read', 'recurse', or 'skip'
  -D, --devices=ACTION      how to handle devices, FIFOs and sockets;
                            ACTION is 'read' or 'skip'
  -r, --recursive           like --directories=recurse
  -R, --dereference-recursive
                            likewise, but follow all symlinks
      --include=FILE_PATTERN
                            search only files that match FILE_PATTERN
      --exclude=FILE_PATTERN
                            skip files and directories matching FILE_PATTERN
      --exclude-from=FILE   skip files matching any file pattern from FILE
      --exclude-dir=PATTERN directories that match PATTERN will be skipped.
  -L, --files-without-match print only names of FILEs containing no match
  -l, --files-with-matches  print only names of FILEs containing matches
  -c, --count               print only a count of matching lines per FILE
  -T, --initial-tab         make tabs line up (if needed)
  -Z, --null                print 0 byte after FILE name

Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context
  -NUM                      same as --context=NUM
      --group-separator=SEP use SEP as a group separator
      --no-group-separator  use empty string as a group separator
      --color[=WHEN],
      --colour[=WHEN]       use markers to highlight the matching strings;
                            WHEN is 'always', 'never', or 'auto'
  -U, --binary              do not strip CR characters at EOL (MSDOS/Windows)
  -u, --unix-byte-offsets   report offsets as if CRs were not there
                            (MSDOS/Windows)

'egrep' means 'grep -E'.  'fgrep' means 'grep -F'.
Direct invocation as either 'egrep' or 'fgrep' is deprecated.
When FILE is -, read standard input.  With no FILE, read . if a command-line
-r is given, - otherwise.  If fewer than two FILEs are given, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.

Report bugs to: bug-grep@gnu.org
GNU Grep home page: <http://www.gnu.org/software/grep/>
General help using GNU software: <http://www.gnu.org/gethelp/>
[root@localhost ~]

grep的用法

命令還是非常多的,把重要的一個一個來試試,不加任何選項,DHCP關鍵詞,/etc/services文本檔案
在這里插入圖片描述
不區分大小寫查找,使用-i
在這里插入圖片描述
一定要匹配上整個單詞的查找,包含或者前后有其余單詞字符的均不匹配,使用-w
在這里插入圖片描述
匹配注釋的空行,這里由于#是特殊符號,需要轉義,使用-x,匹配整行資料
在這里插入圖片描述

匹配注釋的空行,并顯示這些注釋行的行號,使用-n
在這里插入圖片描述
統計匹配注釋的空行的數量,使用-c
在這里插入圖片描述
匹配以#開頭的行數,使用-e引數,但是只能接受一個引數的正則
在這里插入圖片描述

匹配ARP或者DHCP關鍵字的行數,使用-E使用擴展正則,可以使用多個引數進行正則匹配
在這里插入圖片描述
輸出沒有#號的行,使用-v
在這里插入圖片描述
匹配前10#開頭的行數,使用-m
在這里插入圖片描述
顯示DHCP所在的字符數
在這里插入圖片描述
這里將/etc/services分成兩部分,每部分6000

[root@localhost ~]split -l 6000 /etc/services services-
[root@localhost ~]ll services-a*
-rw-r--r-- 1 root root 343604 Feb 11 15:06 services-aa
-rw-r--r-- 1 root root 326689 Feb 11 15:06 services-ab

匹配這兩個檔案中的FTP行,帶-H顯示檔案名
在這里插入圖片描述
匹配這兩個檔案中的FTP行,帶-h不顯示檔案名
在這里插入圖片描述
只匹配關鍵字及其出現的行數,使用-o
在這里插入圖片描述
使用-q,查找后無任何輸出,一般用于shell內進行流程控制

[root@localhost ~]echo "if grep -q DHCP /etc/services; then echo 1; else echo 2;fi" > 1.sh && chmod 777 1.sh
[root@localhost ~]./1.sh 
1
[root@localhost ~]echo "if grep -q aaaaaaaa /etc/services; then echo 1; else echo 2;fi" > 1.sh && chmod 777 1.sh    
[root@localhost ~]./1.sh 
2

對二進制檔案進行處理時的操作

#二進制檔案出錯
[root@localhost ~] grep abc /bin/ls
Binary file /bin/ls matches
#忽略二進制檔案
[root@localhost ~] grep -I abc /bin/ls
#以文本模式讀取二進制檔案
[root@localhost ~] grep -a abc /bin/ls   
ignoring invalid value of environment variable QUOTING_STYLE: %signoring invalid width in environment variable COLUMNS: %signoring invalid tab size in environment variable TABSIZE: %sabcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1  - +FORMAT (e.g., +%H:%M) for a 'date'-style format

在目錄所有的檔案下查找DHCP,使用-r,跳過符號鏈接,如果使用-R則不跳過,
在這里插入圖片描述
在除了http-buildlamp-build目錄外查找FROM關鍵字,使用--exclude-dir
在這里插入圖片描述
只顯示匹配上的檔案名,使用-l,顯示沒有匹配上的檔案名使用-L
在這里插入圖片描述
在使用-n-H等引數時,可以使開頭加上tab,然并卵
在這里插入圖片描述
-A是顯示匹配后和它后面的n
在這里插入圖片描述
-B是顯示匹配行和它前面的n
在這里插入圖片描述
-C是匹配行和它前后各n
在這里插入圖片描述
在使用了-A -B -C的查尋結果后增加分隔符,使用--group-separator
在這里插入圖片描述
還有一些感覺不太常用的方法,比如-z、-Z,-u、-U等都找不到合適的例子來演示,但是我感覺到這grep已經夠用了!


0x02 sed

命令沒有grep多,但是用于替換和進行行數的操作很方便

[root@localhost ~]sed --help
Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...

  -n, --quiet, --silent
                 suppress automatic printing of pattern space
  -e script, --expression=script
                 add the script to the commands to be executed
  -f script-file, --file=script-file
                 add the contents of script-file to the commands to be executed
  --follow-symlinks
                 follow symlinks when processing in place
  -i[SUFFIX], --in-place[=SUFFIX]
                 edit files in place (makes backup if SUFFIX supplied)
  -c, --copy
                 use copy instead of rename when shuffling files in -i mode
  -b, --binary
                 does nothing; for compatibility with WIN32/CYGWIN/MSDOS/EMX (
                 open files in binary mode (CR+LFs are not treated specially))
  -l N, --line-length=N
                 specify the desired line-wrap length for the `l' command
  --posix
                 disable all GNU extensions.
  -r, --regexp-extended
                 use extended regular expressions in the script.
  -s, --separate
                 consider files as separate rather than as a single continuous
                 long stream.
  -u, --unbuffered
                 load minimal amounts of data from the input files and flush
                 the output buffers more often
  -z, --null-data
                 separate lines by NUL characters
  --help
                 display this help and exit
  --version
                 output version information and exit

除此之外在man grep中還可以找到一些常見的方法,詳細用法看示例

  • a,在下面增加
  • i,在上面增加
  • d,洗掉
  • c,整行修改
  • s,部分修改
  • p,列印
  • y,單字替換
  • w,將內容寫入新檔案
  • r,將新檔案插入原檔案
  • q,匹配退出

sed的用法

先用最常見的-e,拷貝/etc/passwd的前五行到本目錄下形成檔案passwd

在第二行下面增加資料

[root@localhost ~]cat passwd | sed -e '2a test!'     
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
test!
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

在第二行上面增加資料

[root@localhost ~]cat passwd | sed -e '2i test!'
root:x:0:0:root:/root:/bin/bash
test!
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

在第二行下面增加兩行資料

[root@localhost ~]cat passwd | sed -e '2a test test \
> haha haha'
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
test test 
haha haha
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

將第二行換成*****

[root@localhost ~]cat passwd |sed -e '2c *********'
root:x:0:0:root:/root:/bin/bash
*********
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

洗掉第三行到最后一行

[root@localhost ~]cat passwd |sed -e '3,$d'
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin

將所有的o換成大寫的O

[root@localhost ~]cat passwd |sed -e 's/o/O/g'
rOOt:x:0:0:rOOt:/rOOt:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nOlOgin
daemOn:x:2:2:daemOn:/sbin:/sbin/nOlOgin
adm:x:3:4:adm:/var/adm:/sbin/nOlOgin
lp:x:4:7:lp:/var/spOOl/lpd:/sbin/nOlOgin

將第二行的o換成大寫的O

[root@localhost ~]cat passwd |sed -e '2s/o/O/g'
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nOlOgin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

將第三行到第四行第一個的o換成大寫的O

[root@localhost ~]cat passwd |sed -e 's/o/O/' 
rOot:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nOlogin
daemOn:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nOlogin
lp:x:4:7:lp:/var/spOol/lpd:/sbin/nologin

將所有的數字都換成*,要注意,前后字符數量一致

[root@localhost ~]cat passwd |sed -e 'y/0123456789/**********/'
root:x:*:*:root:/root:/bin/bash
BIN:x:*:*:BIN:/BIN:/sBIN/nologin
daemon:x:*:*:daemon:/sbin:/sbin/nologin
adm:x:*:*:adm:/var/adm:/sbin/nologin
lp:x:*:*:lp:/var/spool/lpd:/sbin/nologin

在第二行插入分隔符檔案

[root@localhost ~]cat a.txt                
**********
[root@localhost ~]cat passwd |sed -e "2r a.txt"
root:x:0:0:root:/root:/bin/bash
BIN:x:1:1:BIN:/BIN:/sBIN/nologin
**********
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

查尋到關鍵字就退出

[root@localhost ~]cat passwd |sed -e '/nologin/q'
root:x:0:0:root:/root:/bin/bash
BIN:x:1:1:BIN:/BIN:/sBIN/nologin

-n選項為安靜模式,一般和p方法一起用,列印出2-3

[root@localhost ~]cat passwd |sed -n '2,3p'  
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

2-3行資料寫入新檔案,配合-n選項效果更好

[root@localhost ~]cat passwd |sed -n '2,3w test.txt' 
[root@localhost ~]cat test.txt 
BIN:x:1:1:BIN:/BIN:/sBIN/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

比如可以利用正則來獲取IP地址

[root@localhost ~]ifconfig ens32|sed -n '2p'|sed -e 's/ *inet //'|sed -e 's/ *netmask.*//'
10.1.1.222

如果用的-i選項,則是不輸出結果,直接修改原檔案,使用的時候一定要注意

[root@localhost ~]cat passwd 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

[root@localhost ~]sed -i '2s/bin/BIN/g' passwd ;cat passwd 
root:x:0:0:root:/root:/bin/bash
BIN:x:1:1:BIN:/BIN:/sBIN/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sed命令的尋址

前面在介紹各個腳本命令時,我們一直忽略了對 address部分的介紹,對各個腳本命令來說,address用來表明該腳本命令作用到文本中的具體行,通過之前的顯示應該有一定感覺了,再來總結下,

默認情況下,sed 命令會作用于文本資料的所有行,如果只想將命令作用于特定行或某些行,則必須寫明 address 部分,表示的方法有以下 2 種:

  • 以數字形式指定行區間;
  • 用文本模式指定具體行區間,

以上兩種形式都可以使用如下這 2 種格式,分別是:

[address]腳本命令

或者

address {
    多個腳本命令
}

以數字形式指定行區間

```bash
[root@localhost ~]cat passwd |sed -n '2,3p'  
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

以文本指定區間

[root@localhost ~]cat passwd |sed -n '/root/p'
root:x:0:0:root:/root:/bin/bash

使用多腳本命令把所有的uid前后都加上"gid前后加上',這里使用-f選項,呼叫腳本檔案更方便

[root@localhost ~]cat sed.sh 
/[0-9]/{
 s//\"&\"/1
 s//\'&\'/2
}

[root@localhost ~]cat passwd |sed -f sed.sh 
root:x:"0":'0':root:/root:/bin/bash
BIN:x:"1":'1':BIN:/BIN:/sBIN/nologin
daemon:x:"2":'2':daemon:/sbin:/sbin/nologin
adm:x:"3":'4':adm:/var/adm:/sbin/nologin
lp:x:"4":'7':lp:/var/spool/lpd:/sbin/nologin

sed的多行處理

N命令會將下一行文本內容添加到緩沖區已有資料之后(之間用換行符分隔),從而使前后兩個文本行同時位于緩沖區中,sed 命令會將這兩行資料當成一行來處理,

[root@localhost ~] cat data2.txt
This is the header line.
This is the first data line.
This is the second data line.
This is the last line.
[root@localhost ~] sed '/first/{ N ; s/\n/ / }' data2.txt
This is the header line.
This is the first data line. This is the second data line.
This is the last line.

D 命令將緩沖區中第一個換行符(包括換行符)之前的內容洗掉掉,

[root@localhost ~]head -n 10 /etc/services | sed -e 's/\#//g' > services 
[root@localhost ~]cat services 
 /etc/services:
 $Id: services,v 1.55 2013/04/14 ovasik Exp $

 Network services, Internet style
 IANA services version: last updated 2013-04-10

 Note that it is presently the policy of IANA to assign a single well-known
 port number for both TCP and UDP; hence, most entries here have two entries
 even if the protocol doesn't support UDP operations.
 Updated from RFC 1700, ``Assigned Numbers'' (October 1994).  Not all ports

洗掉匹配的第一個空白行,先匹配空行,然后使用N指定將下一行也加入緩沖區,然后利用下一行的Net關鍵字進行匹配洗掉匹配上的第一個換行符及之前的內容,

[root@localhost ~]cat services | sed -e '/^$/{N;/Net/D}' 
 /etc/services:
 $Id: services,v 1.55 2013/04/14 ovasik Exp $
 Network services, Internet style
 IANA services version: last updated 2013-04-10

 Note that it is presently the policy of IANA to assign a single well-known
 port number for both TCP and UDP; hence, most entries here have two entries
 even if the protocol doesn't support UDP operations.
 Updated from RFC 1700, ``Assigned Numbers'' (October 1994).  Not all ports

P命令列印多行資料,還是利用上面的例子,p會輸出匹配上的內容,而P只輸出匹配上內容當中的第一個換行符及之前的內容

[root@localhost ~]cat services | sed -n '/^$/{N;/Net/p}'

 Network services, Internet style
[root@localhost ~]cat services | sed -n '/^$/{N;/Net/P}'

[root@localhost ~]

sed保持空間

相關的命令有5

  • h 將模式空間中的內容復制到保持空間
  • H 將模式空間中的內容附加到保持空間
  • g 將保持空間中的內容復制到模式空間
  • G 將保持空間中的內容附加到模式空間
  • x 交換模式空間和保持空間中的內容

通常,在使用 hH 命令將字串移動到保持空間后,最侄訓要用 gGx 命令將保存的字串移回模式空間,保持空間最直接的作用是,一旦我們將模式空間中所有的檔案復制到保持空間中,就可以清空模式空間來加載其他要處理的文本內容,

由于有兩個緩沖區域,下面的例子中演示了如何用 hg 命令來將資料在 sed 緩沖區之間移動,

[root@localhost ~]# cat data2.txt
This is the header line.
This is the first data line.
This is the second data line.
This is the last line.
[root@localhost ~]# sed -n '/first/ {h ; p ; n ; p ; g ; p }' data2.txt
This is the first data line.
This is the second data line.
This is the first data line.

這個例子的運行程序是這樣的:

  • sed腳本命令用正則運算式過濾出含有單詞first的行;
  • 當含有單詞 first 的行出現時,h 命令將該行放到保持空間;
  • p 命令列印模式空間也就是第一個資料行的內容;
  • n 命令提取資料流中的下一行(This is the second data line),并將它放到模式空間;
  • p 命令列印模式空間的內容,現在是第二個資料行;
  • g 命令將保持空間的內容(This is the first data line)放回模式空間,替換當前文本;
  • p 命令列印模式空間的當前內容,現在變回第一個資料行了,

講道理,還沒完全理解這個可以怎么high,留待將來

sed分支

通常,sed程式的執行程序會從第一個腳本命令開始,一直執行到最后一個腳本命令,sed 提供了 b 分支命令來改變命令腳本的執行流程,其結果與結構化編程類似,

b分支命令基本格式為:

[address]b [label]

其中,address 引數決定了哪些行的資料會觸發分支命令,label 引數定義了要跳轉到的位置,

#原檔案
[root@localhost ~]cat services 
 /etc/services:
 $Id: services,v 1.55 2013/04/14 ovasik Exp $

 Network services, Internet style
 IANA services version: last updated 2013-04-10

 Note that it is presently the policy of IANA to assign a single well-known
 port number for both TCP and UDP; hence, most entries here have two entries
 even if the protocol doesnt support UDP operations.
 Updated from RFC 1700, ''Assigned Numbers'' (October 1994).  Not all ports
 
 #將原檔案中的services改為Services,但是當遇到Network時,就改為SERvices
 [root@localhost ~]cat services  | sed -e '{/Net/b jump;s/ser/Ser/g
> :jump
> s/ser/SER/g}'

 /etc/Services:
 $Id: Services,v 1.55 2013/04/14 ovasik Exp $

 Network SERvices, Internet style
 IANA Services version: last updated 2013-04-10

 Note that it is presently the policy of IANA to assign a single well-known
 port number for both TCP and UDP; hence, most entries here have two entries
 even if the protocol doesnt support UDP operations.
 Updated from RFC 1700, ''Assigned Numbers'' (October 1994).  Not all ports

#如果上述看起來吃力就寫成腳本
[root@localhost ~]cat services  | sed -f sed.sh 
 /etc/Services:
 $Id: Services,v 1.55 2013/04/14 ovasik Exp $

 Network SERvices, Internet style
 IANA Services version: last updated 2013-04-10

 Note that it is presently the policy of IANA to assign a single well-known
 port number for both TCP and UDP; hence, most entries here have two entries
 even if the protocol doesn't support UDP operations.
 Updated from RFC 1700, ``Assigned Numbers'' (October 1994).  Not all ports
 
[root@localhost ~]cat sed.sh 
{/Net/b jump;s/ser/Ser/g
:jump
s/ser/SER/g
}

其實就像編程中的判斷陳述句,當匹配上了條件,就跳過前面的陳述句,執行后面的陳述句,

當然除了向后跳,還可以像前跳,用于回圈處理,比如替換所有的符號*

[root@localhost ~]cat services  | sed -e '{/[[:punct:]]/b start;
>:start
>s/[[:punct:]]/\*/g}'

 *etc*services*
 *Id* services*v 1*55 2013*04*14 ovasik Exp *

 Network services* Internet style
 IANA services version* last updated 2013*04*10

 Note that it is presently the policy of IANA to assign a single well*known
 port number for both TCP and UDP* hence* most entries here have two entries
 even if the protocol doesn*t support UDP operations*
 Updated from RFC 1700* **Assigned Numbers** *October 1994**  Not all ports

但是需要注入,如果b沒有指定label則會直接跳到最后,下方中要講的t命令也是如此,

t類似于 b 分支命令,t 命令也可以用來改變 sed 腳本的執行流程,
t 測驗命令會根據 s 替換命令的結果,如果匹配并替換成功,則腳本的執行會跳轉到指定的標簽;反之,t 命令無效,

#將所有的數字換成*
[root@localhost ~]cat services | sed -e '{
> :start
> s/[[:digit:]]/\*/
> t start}'
 /etc/services:
 $Id: services,v *.** ****/**/** ovasik Exp $

 Network services, Internet style
 IANA services version: last updated ****-**-**

 Note that it is presently the policy of IANA to assign a single well-known
 port number for both TCP and UDP; hence, most entries here have two entries
 even if the protocol doesn't support UDP operations.
 Updated from RFC ****, ``Assigned Numbers'' (October ****).  Not all ports

0x03 awk

感覺是一個比一個復雜,頭痛!

awk主要是用于處理列的資料,查看help確實不多,但是看了下man,恐怖如斯

[root@localhost ~]awk --help
Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
Usage: awk [POSIX or GNU style options] [--] 'program' file ...
POSIX options:          GNU long options: (standard)
        -f progfile             --file=progfile
        -F fs                   --field-separator=fs
        -v var=val              --assign=var=val
Short options:          GNU long options: (extensions)
        -b                      --characters-as-bytes
        -c                      --traditional
        -C                      --copyright
        -d[file]                --dump-variables[=file]
        -e 'program-text'       --source='program-text'
        -E file                 --exec=file
        -g                      --gen-pot
        -h                      --help
        -L [fatal]              --lint[=fatal]
        -n                      --non-decimal-data
        -N                      --use-lc-numeric
        -O                      --optimize
        -p[file]                --profile[=file]
        -P                      --posix
        -r                      --re-interval
        -S                      --sandbox
        -t                      --lint-old
        -V                      --version

To report bugs, see node `Bugs' in `gawk.info', which is
section `Reporting Problems and Bugs' in the printed version.

gawk is a pattern scanning and processing language.
By default it reads standard input and writes standard output.

Examples:
        gawk '{ sum += $1 }; END { print sum }' file
        gawk -F: '{ print $1 }' /etc/passwd

awk命令的基本格式為:

awk [選項] '腳本命令' 檔案名

選項就三個,還挺好理解

  • -F fs ,指定以 fs 作為輸入行的分隔符,awk 命令默認分隔符為空格或制表符,
  • -f file,從腳本檔案中讀取 awk 腳本指令,以取代直接在命令列中輸入指令,
  • -v var=val,在執行處理程序之前,設定一個變數 var,并給其設備初始值為 val,

關鍵還是得在于腳本命令,由兩部分組成,用起來和sed還是非常接近的

'匹配規則{執行命令}'

先看一個簡單的案例

[root@localhost ~]cat services 
 /etc/services:
 $Id: services,v 1.55 2013/04/14 ovasik Exp $

 Network services, Internet style
 IANA services version: last updated 2013-04-10

 Note that it is presently the policy of IANA to assign a single well-known
 port number for both TCP and UDP; hence, most entries here have two entries
 even if the protocol doesnt support UDP operations.
 Updated from RFC 1700, ''Assigned Numbers'' (October 1994).  Not all ports
 #輸出兩個空行所對應的字母
[root@localhost ~]cat services | awk '/^$/{print "bbbbbbbb"}'
bbbbbbbb
bbbbbbbb

awk的用法

awk 'BEGIN{ commands } pattern{ commands } END{ commands }'
  • 第一步:運行BEGIN{ commands }陳述句塊中的陳述句,
  • 第二步:從檔案或標準輸入(stdin)讀取一行,然后運行pattern{ commands }陳述句塊,它逐行掃描檔案,從第一行到最后一行反復這個程序,直到檔案所有被讀取完成,
  • 第三步:當讀至輸入流末尾時,運行END{ commands }陳述句塊,

BEGIN陳述句塊在awk開始從輸入流中讀取行之前被運行,這是一個可選的陳述句塊,比方變數初始化、列印輸出表格的表頭等陳述句通常能夠寫在BEGIN陳述句塊中,

END陳述句塊在awk從輸入流中讀取全然部的行之后即被運行,比方列印全部行的分析結果這類資訊匯總都是在END陳述句塊中完畢,它也是一個可選陳述句塊,

pattern陳述句塊中的通用命令是最重要的部分,它也是可選的,假設沒有提供pattern陳述句塊,則默認運行{ print },即列印每個讀取到的行,awk讀取的每一行都會運行該陳述句塊,

這三個部分缺少任何一部分都可以,

接下來看個例子

[root@localhost ~]ll
total 56
-rw-r--r--  1 root root     8 Feb 10 20:44 -
-rwxrwxrwx  1 root root    63 Feb 11 15:29 1.sh
-rw-r--r--  1 root root     3 Feb 10 21:17 1.txt
-rw-r--r--  1 root root    53 Feb 10 20:34 2.txt
-rw-------. 1 root root  1333 Jan 31 23:26 anaconda-ks.cfg
-rw-r--r--  1 root root    11 Feb 12 11:01 a.txt
-rw-r--r--  1 root root   274 Feb  9 15:04 Dockerfile
drwxr-xr-x  2 root root    24 Feb  8 20:20 http-build
drwxr-xr-x  2 root root    24 Feb  9 19:54 lamp-build
-rw-r--r--  1 root root   183 Feb 12 10:42 passwd
-rw-r--r--  1 root root    36 Feb 12 16:36 sed.sh
-rw-r--r--  1 root root   429 Feb 12 15:04 services
-rw-r--r--  1 root root 10240 Feb 10 21:28 test.tar
-rw-r--r--  1 root root    73 Feb 12 10:58 test.txt

[root@localhost ~]ll | awk '{print $1}'
total
-rw-r--r--
-rwxrwxrwx
-rw-r--r--
-rw-r--r--
-rw-------.
-rw-r--r--
-rw-r--r--
drwxr-xr-x
drwxr-xr-x
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--
-rw-r--r--

在這里awk后面沒有BEGINEND,跟著的是pattern,也就是每一行都會經過這個命令,在awk$n,表示第幾列,在這里表示列印每一行的第一列,

  • $0 當前記錄(這個變數中存放著整個行的內容)
  • $1~$n 當前記錄的第n個欄位,欄位間由FS分隔
  • FS 輸入欄位分隔符 默認是空格Tab
  • NF 當前記錄中的欄位個數,就是有多少列
  • NR 已經讀出的記錄數,就是行號,從1開始,如果有多個檔案話,這個值也是不斷累加中,
  • FNR 當前記錄數,與NR不同的是,這個值會是各個檔案自己的行號
  • RS 輸入的記錄分隔符, 默認為換行符
  • OFS 輸出欄位分隔符, 默認也是空格
  • ORS 輸出的記錄分隔符,默認為換行符
  • FILENAME 當前輸入檔案的名字

列印每一行的行數

[root@localhost ~]ll | awk '{print NR  "\t" $1}' 
1       total
2       -rw-r--r--
3       -rwxrwxrwx
4       -rw-r--r--
5       -rw-r--r--
6       -rw-------.
7       -rw-r--r--
8       -rw-r--r--
9       drwxr-xr-x
10      drwxr-xr-x
11      -rw-r--r--
12      -rw-r--r--
13      -rw-r--r--
14      -rw-r--r--
15      -rw-r--r--

再來看一下格式化輸出

[root@localhost ~]awk  -F ':'  '{printf("filename:%10s,linenumber:%s,columns:%s,linecontent:%s\n",FILENAME,NR,NF,$0)}' /etc/passwd
filename:/etc/passwd,linenumber:1,columns:7,linecontent:root:x:0:0:root:/root:/bin/bash
filename:/etc/passwd,linenumber:2,columns:7,linecontent:bin:x:1:1:bin:/bin:/sbin/nologin
filename:/etc/passwd,linenumber:3,columns:7,linecontent:daemon:x:2:2:daemon:/sbin:/sbin/nologin
filename:/etc/passwd,linenumber:4,columns:7,linecontent:adm:x:3:4:adm:/var/adm:/sbin/nologin
filename:/etc/passwd,linenumber:5,columns:7,linecontent:lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
filename:/etc/passwd,linenumber:6,columns:7,linecontent:sync:x:5:0:sync:/sbin:/bin/sync
filename:/etc/passwd,linenumber:7,columns:7,linecontent:shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
filename:/etc/passwd,linenumber:8,columns:7,linecontent:halt:x:7:0:halt:/sbin:/sbin/halt
filename:/etc/passwd,linenumber:9,columns:7,linecontent:mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
filename:/etc/passwd,linenumber:10,columns:7,linecontent:operator:x:11:0:operator:/root:/sbin/nologin
filename:/etc/passwd,linenumber:11,columns:7,linecontent:games:x:12:100:games:/usr/games:/sbin/nologin
filename:/etc/passwd,linenumber:12,columns:7,linecontent:ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
filename:/etc/passwd,linenumber:13,columns:7,linecontent:nobody:x:99:99:Nobody:/:/sbin/nologin
filename:/etc/passwd,linenumber:14,columns:7,linecontent:systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
filename:/etc/passwd,linenumber:15,columns:7,linecontent:dbus:x:81:81:System message bus:/:/sbin/nologin
filename:/etc/passwd,linenumber:16,columns:7,linecontent:polkitd:x:999:998:User for polkitd:/:/sbin/nologin
filename:/etc/passwd,linenumber:17,columns:7,linecontent:sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
filename:/etc/passwd,linenumber:18,columns:7,linecontent:postfix:x:89:89::/var/spool/postfix:/sbin/nologin
filename:/etc/passwd,linenumber:19,columns:7,linecontent:apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

awk也可以使用語法,比如ifwhile等都是借鑒于C語言,,,比如選擇出/etc/passwduid小于5的用戶名及uid

[root@localhost ~]cat /etc/passwd | awk -F ":" '$3<5 {print $1 "\t" $3}' 
root    0
bin     1
daemon  2
adm     3
lp      4

比如可以借用變數,用來計算1100的和

[root@localhost ~]   awk 'BEGIN{for(i=1;i<=100;i++){test+=i}print test}' 
5050

實在是太狠了,慢慢來吧,以后在實戰中體會,嘿嘿,

最后再用awk獲取ip地址,在處理資料上感覺比sed好用多了,強大!

[root@localhost ~]ifconfig ens32|awk '/inet /{print $2}'
10.1.1.222

最后,用大年三十和年初一完成的長篇攻略,祝大家牛年大吉,牛氣沖天!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/259153.html

標籤:其他

上一篇:DHCP和DHCPSnooping

下一篇:ubuntu18.04組軟RAID1和10及修復

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more