linux(centos8):用cut顯示文本內容的指定列


一,cut命令的用途

從一個文本文件或者文本流中提取文本列

分別用: 字節、字符、字段 作為單位進行提取

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,查看cut命令所屬的包

[root@blog ~]$ whereis cut
cut: /usr/bin/cut /usr/share/man/man1/cut.1.gz /usr/share/man/man1p/cut.1p.gz

[root@blog ~]$ rpm -qf /usr/bin/cut
coreutils-8.30-6.el8.x86_64

 

如果提示找不到命令或命令被誤刪除,

可以用dnf安裝

[root@blog ~]$ dnf install coreutils

 

三,查看cut命令的版本和幫助

1,查看版本

[root@blog ~]$ cut --version
cut (GNU coreutils) 8.30
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by David M. Ihnat, David MacKenzie, and Jim Meyering.

 

2,查看幫助

[root@blog ~]$ cut --help

 

3,查看手冊

[root@blog ~]$ man cut

 

四,cut命令在運維中的使用例子:

1,顯示nginx日志中所有的ip

# -d:指定分隔字段的分隔符,默認的分隔符是tab

#-f: 指定顯示第幾個字段

[root@blog nginxlogs]$ cut -d ' ' -f 1 file_meet.access_log
106.15.200.123
47.101.200.88
...

 

類似的還有:

第7列是url(使用空格作分隔符)

[root@blog nginxlogs]$ cut -d ' ' -f 7 file_meet.access_log
/
/web2/images/h4.png
/web2/images/h10.png 
...

 

用雙引號做分隔符,第6列是user agent

[root@blog nginxlogs]$ cut -d '"' -f 6 file_meet.access_log | more
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0
...

 

2,列出所有有權登錄bash的用戶

# -d:指定分隔字段的分隔符,默認的分隔符是tab

#-f: 指定顯示第幾個字段

[root@blog ~]$ grep '/bin/bash' /etc/passwd | cut -d ':' -f 1,7
root:/bin/bash
webop:/bin/bash

 

說明:上面的命令效果等同於:

#--complement:  顯示-f指定字段以外的其他字段

[root@blog ~]$ grep '/bin/bash' /etc/passwd | cut -d ':' -f 2,3,4,5,6 --complement

也等同於

[root@blog ~]$ grep '/bin/bash' /etc/passwd | cut -d ':' -f 2-6 --complement

 

3,打印每個分區和使用的占比

#sed '1d' :去掉第一行的表頭

#tr -s:--squeeze-repeats:縮減連續重復的字符成指定的單個字符

[root@blog ~]$ df -h | sed '1d' | tr -s ' ' | cut -d ' ' -f 1,5
devtmpfs 0%
tmpfs 0%
tmpfs 1%
tmpfs 0%
/dev/vda1 15%
/dev/vdb1 1%
tmpfs 0%

說明:df 命令輸出的部分空格較多,數量不一致,

          我們用tr做一下壓縮,這樣方便cut讀取

 

4,打印每個分區和使用的占比,字段之間用-分隔

#--output-delimiter='-' 輸出時的分隔符也可以指定

#tr -d '%'   去掉百分比符號

[root@blog ~]$ df -h | sed '1d' | tr -s ' ' | cut -d ' ' -f 1,5 --output-delimiter='-' | tr -d '%'
devtmpfs-0
tmpfs-0
tmpfs-1
tmpfs-0
/dev/vda1-15
/dev/vdb1-1
tmpfs-0

 

5,用cut截取每行的前5個字符

#-c:截取指定位置的字符

[root@blog ~]$ cut -c1-5 /etc/passwd 

 

6,其他參數:

-s:--only-delimited 不包含分隔符的行直接不顯示 ( do not print lines not containing delimiters)

-b: 以字節為單位進行分割

 

五,查看centos的版本

[root@blog nginxlogs]$ cat /etc/redhat-release
CentOS Linux release 8.0.1905 (Core)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM